# Load VIMS Default Company Settings

import os
import sys
import mysql.connector

try:
	import cElementTree as ET
except ImportError:
	try:
# Python 2.5 need to import a different module
		import xml.etree.cElementTree as ET
	except ImportError:
		exit_err("Failed to import cElementTree from any known place")      

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))
		
def defaultSettings():
	defaults = {}
# Parse a xml file (specify the path)
#	def_file = os.path.join(dir_path, '../vimsconfig/systemsettings.xml')
	def_file = "f:/webroot/rdtkuk/vimsconfig/systemsettings.xml"
	try:
		dom = ET.parse(open(def_file, "r"))
		root = dom.getroot()
	except:
		exit_err("Unable to open and parse input definition file: " + def_file)
		
	for system in root.iter('system'):
		for setting in system:
			if ((setting.tag.lower() == "systemid") and (setting.text.lower() == "default")):
				for setting in system:
					defaults[setting.tag] = str(setting.text)
	return defaults

def companySettings(defaults):
	cnx = mysql.connector.connect(user=defaults['dbuser'], password=defaults['dbpwd'],host=defaults['dbhost'],database=defaults['dbase'])
	try:
		dataQuery = "SELECT * FROM company WHERE id="+defaults['company']+" LIMIT 1"
		cursor = cnx.cursor(dictionary=True)
		cursor.execute(dataQuery)
		data = cursor.fetchall()
		for row in data:
			defaults['interfacein'] = (row['interface_input'])
			defaults['interfaceout'] = (row['interface_output'])
	except mysql.connector.Error as err:
		print('Update Error',err,'-',dataQuery)
		
	finally:
		try:
			cursor.close()
			cnx.close()
		except:
			pass
			
	return defaults

def main():
	defaults = defaultSettings()
	defaults = companySettings(defaults)
	
	if (len(sys.argv)>1):
		if (sys.argv[1] == "interfacein"):
			sys.stdout.write(defaults['interfacein'])
		if (sys.argv[1] == "interfaceout"):
			sys.stdout.write(defaults['interfaceout'])
		sys.exit(0)
		
#	print("defaults:",defaults)

if __name__ == '__main__':
	main()

#	print(defaults)