#!/usr/bin/python3

import readline

import traceback

import argparse
import sqlite3

import os.path
import time

import shlex # THIS IS WONDERFUL

from commands import *
from SitDatabase import *

# Copied directly from SO #287871
class Cols:
	HEADER = '\033[95m'
	OKBLUE = '\033[94m'
	OKGREEN = '\033[92m'
	WARNING = '\033[93m'
	FAIL = '\033[91m'
	ENDC = '\033[0m'
	BOLD = '\033[1m'
	UNDERLINE = '\033[4m'

class SitSession:
	def __init__(self, db):
		self.props = {}
		self.db = db
		# default properties
		self.props['user'] = None
		self.props['project'] = None
		self.props['task'] = None
	def set_db(self):
		self.db = db
	def get_db(self):
		return self.db
	def set_prop(self, key, val):
		self.props[key] = val
	def get_prop(self, key):
		return self.props[key]
	def require(self, key):
		if self.props[key] is None:
			raise CommandException("No "+key+" selected")
		return self.props[key]

class SitOperator:
	def __init__(self, sess):
		self.sess = sess
		self.s = None
	def run(self):

		scf = SitCommandFactory(self.sess)
		self.s = scf.get_sit()

		while True:
			dirln = Cols.WARNING + "NULL" + Cols.ENDC
			project = self.sess.get_prop("project")
			task = self.sess.get_prop("task")
			if project is not None:
				dirln = Cols.OKGREEN
				dirln += project + Cols.ENDC
			if task is not None:
				dirln += ":"
				dirln += Cols.OKBLUE
				dirln += task + Cols.ENDC
			# print(dirln+"> ", end='')
			cmd = input(dirln+"> ")
			if cmd == "exit":
				break
			try:
				self.do(cmd)
			except CommandException as e:
				print(str(e))
			except Exception as e:
				traceback.print_exc()
			else:
				pass

	def do(self, cmd):
		args = shlex.split(cmd)
		self.s.run(args)
		pass

def main(fn):
	newFile = True
	if (os.path.isfile(fn)):
		newFile = False

	conn = sqlite3.connect(fn)
	db = SitDatabase(conn)

	db.generate_tables()

	p = SitOperator(SitSession(db))
	p.run()


parser = argparse.ArgumentParser(description='Log work history to file.')
parser.add_argument('filename', type=str)
args = parser.parse_args()

fn = args.filename
main(fn)

# conn = sqlite3.connect('test.db')

# c = conn.cursor()
