import os, ujson
from machine import Pin, PWM
from math import floor
from time import sleep

from thpath import path
from boot import lcd1, show_details, Log
from connections import Connection

# LED Colors
#
# If a trichromatic LED is installed, it will light according to the following rules.
#
# White: Idle
# Red: Error (Not Implemented)
# Green: Running
# Yellow: Installing / uninstalling
# Cyan: Disk access
# Magenta: Network
#
# If 3 seperate monochromatic LEDs are installed, the colors will be split into their respective components.
# Yellow = Red + Green
# Cyan = Green + Blue
# Magenta = Red + Blue
# White = Red + Green + Blue

class ServerError(Exception):...

log = Log(__file__)

class Replace:
	def __init__(self, rep: dict={}):
		self.replist = rep
	
	def __call__(self, string):
		return self.replace(string)

	def __setitem__(self, key, val):
		self.replist[key] = val

	def __getitem__(self, key):
		return self.replist[key]

	def replace(self, string):
		for key, val in self.replist.items():
			string = string.replace(key,val)
		return string

class LED:
	def __init__(self,r,g,b):
		self.r = PWM(r)
		self.g = PWM(g)
		self.b = PWM(b)

		self.freq(512)
		self.value(0,0,0)

	def u8_to_u16(self,u8):
		return floor((u8 / 256) * 65535)

	def freq(self,freq):
		self.r.freq(freq)
		self.g.freq(freq)
		self.b.freq(freq)

	def value(self,r,g,b):
		self.r.duty_u16(self.u8_to_u16(r))
		self.g.duty_u16(self.u8_to_u16(g))
		self.b.duty_u16(self.u8_to_u16(b))
		self.rb, self.gb, self.bb = r, g, b

	def get_value(self):
		return self.rb, self.gb, self.bb

	def red(self,brightness=256):
		self.value(brightness,0,0)

	def green(self,brightness=256):
		self.value(0,brightness,0)

	def blue(self,brightness=256):
		self.value(0,0,brightness)

	def yellow(self,brightness=256):
		self.value(brightness,brightness,0)

	def cyan(self,brightness=256):
		self.value(0,brightness,brightness)

	def purple(self,brightness=256):
		self.value(brightness,0,brightness)

	def off(self):
		self.value(0,0,0)

	def white(self,brightness=256):
		self.value(brightness,brightness,brightness)
	
	def on(self,brightness=256):
		self.white(brightness)

class Version:
	def __init__(self, version: str):
		self.version = version

	def __str__(self):
		return self.version

	def __iter__(self):
		return iter(self.digits())

	def __getitem__(self, item: int):
		return self.digits()[item]

	def digits(self) -> list[int]:
		return [int(digit) for digit in self.version.split('.')]

	def __len__(self) -> int:
		return len(self.digits())

	def __eq__(self, other):
		if len(self) != len(other):return False
		for i, digit in enumerate(self):
			if digit != other[i]:return False
		return True

	def __gt__(self, other):
		for i, digit in enumerate(self):
			if i >= len(other):
				return True
			if digit > other[i]:
				return True
		else:
			return False

	def __lt__(self, other):
		for i, digit in enumerate(self):
			if i >= len(other):
				return False
			if digit < other[i]:
				return True
		else:
			if len(self) < len(other):
				return True
			return False

def callback_msg(message, reason):
	print(f'[{reason}]: {message}')

class AppManager:
	def __init__(
		self, 
		uri,
		dbpath='/apptools.json',
		install_dir='/apps'
	):
		self.uri = uri
		self.rep = Replace({'{url}': uri, '{uri}': uri})
		self.dbpath = dbpath
		self.install_dir = install_dir
		self.led = LED(Pin(18),Pin(19),Pin(20))
		self.brightness = 64
		self.conn = Connection(default_callback_msg=callback_msg)
		self.conn.connect(uri)

	def load_db(self):
		if not path.exists(self.dbpath):
			self.save_db({})
		with open(self.dbpath) as f:
			return {
				'installed': {},
				'exec': {},
				'uninstall': {},
				'depends': {},
				'required-by': {}
			} | ujson.load(f)

	def save_db(self, db):
		with open(self.dbpath, 'w') as f:
			ujson.dump(db,f)

	def list_installed(self):
		db = self.load_db()
		return [app for app, version in db['installed'].items() if version is not None]

	def is_installed(self, app):
		db = self.load_db()
		return db['installed'].get(app) is not None

	def installed_version(self, app):
		db = self.load_db()
		return Version(db['installed'].get(app))

	def run(self, app):
		db = self.load_db()
		if not db['installed'].get(app):
			raise RuntimeError('App not installed.')
		if db['exec'].get(app) == None:
			raise RuntimeError('App is not executable.')
		log.info(f'Loading {app}')
		module = __import__(db['exec'][app].replace('.py',''),['/' + '/'.join(db['exec'][app].split('/')[:-1])])
		log.info(f'LAUNCH: {app}')
		module.main()
		log.info(f'FINISH: {app}')
		del module

	def update(self):
		log.info('Updating app list...')
		resp = self.conn.get(self.uri + '/apps.json')
		with open('/apps.json', 'w') as f:
			f.write(resp.text)

	def get_default_app(self):
		log.info('Getting default app...')
		resp = self.conn.get(self.uri + '/defaultapp.json')
		if resp.response_code != 200:
			raise ServerError
		return resp.json()['name']

	def get_app_index(self, app):
		if not path.exists('/apps.json'):
			self.update()
		with open('/apps.json') as f:
			apps = ujson.load(f)
		return self.rep.replace(apps[app])

	def get_app_location(self, app, version=None):
		index = self.get_app_index(app)
		resp = self.conn.get(index + '/index.json')
		versions = resp.json()['versions']
		if version is None:
			version = max([Version(ver) for ver in versions])
		return index + '/' + str(version)

	def get_app_data(self, uri):
		resp = self.conn.get(uri + '/app.json')
		return resp.json()

	def installable_versions(self, app) -> list[str]:
		log.info('Inspecting installable versions...')
		resp = self.conn.get(self.get_app_index(app) + '/index.json')
		return resp.json()['versions']

	def install(self, app, version=None):
		loc = self.get_app_location(app, version=version)
		self.install_uri(loc)

	def install_uri(self, uri):
		db = self.load_db()
		app_data = self.get_app_data(uri)
		app_name = app_data['name']
		self.rep['{home}'] = self.install_dir + '/' + app_name
		self.rep['{source}'] = uri

		uninstall_data = {'rmfiles': [], 'rmtree': []}

		# Install files
		for source, install_path in app_data['install']['files'].items():
			install_path = self.rep(install_path)
			install_dir = path.dirname(install_path)
			if not path.exists(install_dir):
				path.makedirs(install_dir)
				uninstall_data['rmtree'].append(install_dir)
			resp = self.conn.get(self.rep(source))
			with open(install_path, 'wb') as f:
				f.write(resp.content)
				uninstall_data['rmfiles'].append(install_path)

		db['installed'][app_name] = app_data['version']
		db['exec'][app_name] = self.rep(app_data['exec'])
		db['uninstall'][app_name] = uninstall_data
		self.save_db(db)

	def uninstall(self, app):
		db = self.load_db()

		for file in db['uninstall'][app]['rmfiles']:
			path.remove(file)
		for directory in db['uninstall'][app]['rmtree']:
			path.rmtree(directory)

		del db['installed'][app]
		del db['exec'][app]
		del db['uninstall'][app]
		self.save_db(db)
