#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys,importlib,os,shutil
import database2text.tool as dbtt

class main(object):
	def __init__(self):
		self.readconfig()
	def readconfig(self):
		fn="dbt.txt"
		if len(sys.argv)>1:
			fn=sys.argv[1]
		if not os.path.isfile(fn):
			print("can't open %s. you must create it or tell us another file name." %(fn))
			print("for help, we copy the sample file(dbt_*.txt) to you, enjoy it!")
			sampledir=os.path.join(os.path.dirname(os.path.abspath(dbtt.__file__)),"datafile","sample")
			for f in os.listdir(sampledir):
				if not os.path.exists(f):
					shutil.copy2(os.path.join(sampledir,f),".")
			sys.exit(-1)
		f=open(fn)
		section="global"
		storidata=[]
		stdata={}
		for s in f.readlines():
			if s.startswith(":"):
				if section=="global":
					driver=stdata["driver"]
					dbt=importlib.import_module('database2text.%s' %(stdata["driver"]))
				if not dbt:
					print("can't find driver=xxx , need it in begin of config's file")
					sys.exit(-1)
				if section!="global":
					if not hasattr(dbt,section):
						print("can't find function %s in driver %s" %(section,driver))
						sys.exit(-2)
					getattr(dbt,section)(stdata,storidata)
				section=s[1:].strip()
				storidata=[]
				stdata={}
				continue
			storidata.append(s)
			s=s.rstrip()
			if s.find("=")>=0:
				name=s[:s.find("=")].strip()
				value=s[s.find("=")+1:].strip()
				stdata[name]=value

if __name__ == "__main__":
	main()
