from jivi.fs import *
import configparser
import os
import sys
import win32com.client
def jread(fp,encoding='utf-8'):
	with open(fp,"r",encoding=encoding) as f:
		s = f.read()
		a = json.loads(s)
		return a
"""
wd
arg
propath



"""

class Environment:
	def __init__(self,fp,file_types=['ininame','pf'],sections=['Startup','Colors','fonts']):
		self.file_types = file_types
		self.sections = sections
		shell = win32com.client.Dispatch("WScript.Shell")
		self.shortcut = shell.CreateShortCut(fp)
		self.path = self.shortcut.Targetpath
		
		self.wd = self.shortcut.WorkingDirectory
		self.arg = {}
		self.propath = []
		self.set_arg()
		
		self.set_files()
	def set_arg(self):
		arg = [a for a in [a.strip() for a in self.shortcut.Arguments.split(' ')] if a]
		meep = []
		key = 0
		for a in arg:
			if a.startswith('-'):
				if key:
					self.arg[key] = ' '.join(meep)
					meep = []
				key = a[1:]
				
			elif key:
				meep.append(a)

		if key:
			self.arg[key] = ' '.join(meep)
			
		for k,v in self.arg.items():
			if not hasattr(self,k):
				setattr(self,k,v)
		
				
		for a in self.file_types:
			if a in self.arg:
				if not os.path.isfile(self.arg[a]):
					self.arg[a] = os.path.join(self.wd,self.arg[a])
					
			
			
		self.set_sections()
		
		new_args = []
		for k,v in self.arg.items():
			vv = v
			if k == 'p':
				vv = r"C:\prog\jv\py\dbstruct.p"
			new_args.append("-{k} {v}".format(k=k,v=vv))
		#os.system("{path} {new_args}".format(path=self.path,new_args=" ".join(new_args)))
		self.tabs = {}
		for a in ['ttField','ttIndex','ttIndexField','ttFile']:
			self.tabs[a[2:].lower()] = jread(r"C:\temp\{a}.json".format(a=a))[a]
		

	def set_files(self):
		self.files = []
		tab = {}
		self.files_pp = {}
		
		for d in self.propath:
			for fp in Dir.files(d,ex=['w','p','i'],full=1,deep=1):
				fp = fp.lower()
				tab[fp] = 1
				
		for fp in tab.keys():
			pp = []
			for p in self.propath:
				if fp.startswith(p):
					file_pp = fp[len(p):]
					if not file_pp in self.files_pp:
						self.files_pp[file_pp] = fp
					pp.append(file_pp)
			
			self.files.append(dict(fp=fp,pp=pp,ex=File.ex(fp).lower()))

		
	
	def fp(self,fp):
		if os.path.isfile(fp):
			return os.path.abspath(fp)
		
		for d in self.propath:
			x = os.path.join(d,fp)
			if os.path.isfile(x):
				return os.path.abspath(x)
			

		return 0

	def fp_dir(self,fp):
		if not os.path.isdir(fp):
			fp = os.path.join(self.wd,fp)
		if not os.path.isdir(fp):
			return 0
		return os.path.abspath(fp).rstrip(os.sep) + os.sep
	def set_sections(self):
		
		config = configparser.ConfigParser(strict=0)
		config.read(self.arg['ininame'])
		
		for a in self.sections:
			t = {}
			sn = a.lower()
			if a in config:
				ca = config[a]
				for x in ca:
					t[x.lower()] = ca[x]
					
			setattr(self,sn,t)
		
		
		for a in self.startup['propath'].split(','):
			fp = self.fp_dir(a.strip())
			if fp:
				self.propath.append(fp.lower())
		