#!/usr/bin/env python

'''
Created on Dec 8, 2015

@author: Patrick McDonagh
'''

import time
import sqlite3 as lite
from tag.tag_sqlite import Tag
import traceback

# con = lite.connect("/usr/db/data.db")
con = lite.connect('/mnt/usb/data.db')

configProperties = {}


def main():


	with con:
		cur = con.cursor()
		query = "SELECT * FROM tags WHERE deleted = 0;"
		cur.execute(query)
		tags = cur.fetchall()

	configObj = {}


	with con:
		cur = con.cursor()
		query = "SELECT parameter, val FROM config GROUP BY parameter;"
		cur.execute(query)
		config = cur.fetchall()
	for x in config:
		configObj[x[0]] = x[1]

	try:
		configProperties['PLC_IP_ADDRESS'] = str(configObj['ip_address'])
		print("FYI, using PLC IP Address from the database {0}".format(configProperties['PLC_IP_ADDRESS']))
	except KeyError:
		print("FYI, there is no PLC IP Address stored in the database, defaulting to 192.168.1.10")
		configProperties['PLC_IP_ADDRESS'] = "192.168.1.10"

	try:
		configProperties['plc_type'] = str(configObj['plc_type'])
		print("FYI, using PLC Type from the database {0}".format(configProperties['plc_type']))
	except KeyError:
		print("FYI, there is no PLC Type stored in the database, defaulting to CLX")
		configProperties['plc_type'] = "CLX"

	try:
		configProperties['scan_rate'] = int(configObj['scan_rate'])
		print("FYI, using Scan Rate from the database {0}".format(configProperties['scan_rate']))
	except KeyError:
		print("FYI, there is no Scan Rate stored in the database, defaulting to 10 seconds")
		configProperties['scan_rate'] = 10

	try:
		sa_test = str(configObj['save_all'])
		if sa_test.lower() == "true":
			configProperties['save_all'] = True
		elif sa_test.lower() == "false":
			configProperties['save_all'] = False
		else:
			configProperties['save_all'] = "test"
		print("FYI, value for save_all is {0}".format(configProperties['save_all']))
	except KeyError:
		print("FYI, there is no save_all value stored in the database, using 'test'")
		configProperties['save_all'] = 'test'





	tag_store = {}

	if len(tags) > 0:
		for t in tags:
			# (1, u'Pump Intake Pressure', u'5', u'Pump_Intake_Pressure', u'Pressure at the Intake of the Pump', None, 100.0, 3600, u'PSI', 0.0, 3000.0, u'2016-04-13 21:27:01', 0)
			tag_store[t[1]] = Tag(t[1], t[3], t[0], t[5], t[6], t[7], mapFn=t[8], device_type=configProperties['plc_type'], ip_address=configProperties['PLC_IP_ADDRESS'])


		while True:
			for tag in tag_store:
				try:
					tag_store[tag].read(configProperties['save_all'])
				except:
					print("ERROR EVALUATING {}".format(tag))
					traceback.print_exc()
			time.sleep(configProperties['scan_rate'])

if __name__ == '__main__':
	main()
