import time
from time import sleep
import ujson as json # pyright: ignore[reportMissingModuleSource]

from boot import lcd1 # pyright: ignore[reportMissingModuleSource]
from lcdata import Slide, TickingGroup, StaticProgressBar
from connections import Connection, get, ConnectionError

def dict_merge(self: dict, other: dict) -> dict:
	final = {}
	for key, val in other.items():
		if key in self:
			if type(val) is dict and type(self[key]) is dict:
				final[key] = dict_merge(self[key], val)
			else:
				final[key] = val
		else:
			final[key] = val
	for key, val in self.items():
		if key not in final:
			final[key] = val
	return final

def fmt_time(seconds: int) -> str:
	return f'{seconds // 60:0>2}:{seconds % 60:0>2}'

default_conf = {
	'fields': {
		key: {'visible': False} for key in [
			'title',
			'artist',
			'album',
			'player-name',
			'progress',
			'duration',
			'progress-bar'
		]
	},
	'static': {
		'character': {},
		'bitmap': {}
	},
	'dynamic': {
		'message': {
			'msg_noplayers': '(no players)',
			'msg_notitle': '(no title)',
			'msg_noartist': '(unknown)',
			'msg_noalbum': '',
			'status_paused': 'Playing',
			'status_playing': 'Paused'
		}
	}
}

with open('/lcdplay.json') as f:
	conf = dict_merge(default_conf, json.load(f))


fields = conf['fields']
static = conf['static']
bitmaps = static['bitmap']
characters = static['character']
dynamic = conf['dynamic']
messages = dynamic['message']
MSG_NOPLAYERS = messages['msg_noplayers']
MSG_NOTITLE = messages['msg_notitle']
MSG_NOARTIST = messages['msg_noartist']
MSG_NOALBUM = messages['msg_noalbum']
STATUS_PLAYING = messages['status_playing']
STATUS_PAUSED = messages['status_paused']

for character_num, bitmap in {i: bitmaps.get(f'chr{i}') for i in range(8)}.items():
	if bitmap is None:continue
	lcd1.set_custom_char(character_num, bitmap)

for character, positions in characters.items():
	for position in positions:
		lcd1.set_cursor_pos(*position)
		lcd1.putch(character)

s_player_name = Slide(lcd1, '', **fields['player-name'])
s_title = Slide(lcd1, '(title)', **fields['title'])
s_artist = Slide(lcd1, '(artist)', **fields['artist'])
s_album = Slide(lcd1, '(album)', **fields['album'])
s_progress = Slide(lcd1, '--:--', **fields['progress'])
s_duration = Slide(lcd1, '--:--', **fields['duration'])
s_bar = StaticProgressBar(lcd1, **fields['progress-bar'])
tg = TickingGroup([s_player_name, s_title, s_artist, s_album, s_progress, s_duration, s_bar], tick_on_render=True)

lcd1.set_display_props(True, False, False)
con = Connection()
prev_second = 0
seconds_until_refresh = 0
mtitle = '(title)'
martist = '(artist)'
malbum = '(album)'
mprogress_ms = 0
mprogress = '--:--'
mduration_ms = 0
mduration = '--:--'
primary_player = None
try:
	while True:
		if seconds_until_refresh <= 0:
			seconds_until_refresh = 5
			try:
				resp = con.get('http://doomslayer.local:7529/lcdplay', keep_alive=True)
				if resp.response_code in [200] and resp.headers.get('content-type') == 'application/json':
					media = resp.json()
					primary_player = list(media.keys())[0] if len(media.keys()) != 0 else None if primary_player not in media else primary_player
					media = media[primary_player] if primary_player in media else {}
					mtitle = media['title'] if media.get('title') is not None else MSG_NOTITLE
					martists = ', '.join(media['artists']) if media.get('artists') is not None else MSG_NOARTIST
					malbum = media['album'] if media.get('album') is not None else MSG_NOALBUM
					mprogress_ms = media['progress_ms'] if 'progress_ms' in media else 0
					mduration_ms = media['duration_ms'] if 'duration_ms' in media else 0
					s_title.text = mtitle if primary_player is not None else MSG_NOPLAYERS
					s_artist.text = martists
					s_album.text = malbum
					s_player_name.text = primary_player if primary_player is not None else MSG_NOPLAYERS
				else:
					s_title.text = 'Error!'
					s_artist.text = 'The server encountered an error'
					s_album.text = ''
			except ConnectionError:
				s_title.text = 'Connection error'
				s_artist.text = 'Could not connect to the server.'
				s_album.text = ''
				s_player_name.text = ''
				mduration_ms = 0
		while (c_second := time.localtime()[5]) == prev_second:pass
		mprogress_ms += 1000
		mprogress_ms = mduration_ms if mprogress_ms > mduration_ms else mprogress_ms
		if mprogress_ms == mduration_ms:seconds_until_refresh = 0
		mprogress = str(fmt_time(mprogress_ms // 1000) if mduration_ms > 0 else '--:--')
		mduration = str(fmt_time(mduration_ms // 1000) if mduration_ms > 0 else '--:--')
		s_progress.text = mprogress
		s_duration.text = mduration
		s_bar.value = mprogress_ms / mduration_ms if mduration_ms > 0 else 0
		prev_second = c_second
		seconds_until_refresh -= 1
		tg.render()
except KeyboardInterrupt:
	tg.render_off()
	lcd1.clear()
	lcd1.set_display_props(True, True, True)

__version__ = '0.1.0'
__author__ = 'Rowan Denny'
__email__ = 'iweartwohats@gmail.com'
