import gui
import ustruct as us
import gnss
import vbox
import vts
import os
import gc
from screenshot import screenshot_cb
from picture_button import Picture_Button
from image import Image_Bank
from gui_utils import Colours
from screen_utils import ScreenManager, LiveDisplayParameter, LiveDisplayValue
from screen_base import ScreenBase
from unit_info import Unit
from application import Application, default_cb, Task
from vbo import upy_channel, write_upy_channels, pending_samples as vbo_pending_samples, set_appinfo
from constants import MS_PER_DAY



def gnss_cb():
    while vbox.samples_pending():
        sample = vbox.get_sample_hp()
        Application.Data.sats = sample.sats_used
        Application.Data.fix_type = sample.fix_type
        Application.Data.speed_ms = sample.speed_gnd_mps
        Application.Data.tod_ms = sample.tod_ms
        Application.Data.lat_degE7 = sample.lat_degE7
        Application.Data.lng_degE7 = sample.lng_degE7
        Application.Data.heading_raw = sample.heading_deg
        Application.Data.alt_msl_m = sample.alt_msl_m

    ScreenManager.Current_Screen.new_data_cb()


class MainScreen(ScreenBase):
    def __init__(self):
        super().__init__()
        self.latitude = LiveDisplayValue(0, '{:.7f}')
        self.longitude = LiveDisplayValue(0, '{:.7f}')
        self.height = LiveDisplayValue(0, '{:.2f}', max=9999.9)
        self.speed = LiveDisplayValue(0, '{:.1f}', max=999.9)
        self.picture_buttons = [Application.Icons.get_picture_button('GNSS'),
                                Application.Icons.get_picture_button('Media'),
                                Application.Icons.get_picture_button('Record'),
        ]

    def vsync_cb(self, l):
        super().vsync_cb(l)
        pass

    def press_cb(self, press):
        #currently disabled in normal app as it can cause sample loss
        print(press)
        if (press[0] == 2) and press[1] == 1 and press[2] == 2:
            Application.coldstart_cb(1)

    def setup(self):
        super().setup()
        self.speed.set_scale(2.2369362921) #m/s to Mph
        self.latitude.set_scale(0.0000001) #m/s to Mph
        self.longitude.set_scale(0.0000001) #m/s to Mph
        y_offset = 75
        self.gui_list.extend([
            # gui.SUBLIST,
            [gui.CTRL_TEXT, 400, 450, 31, gui.OPT_CENTER, "Racelogic Tunnel Test"],
            [gui.DL_COLOR_RGB(0, 0, 0)],
            [gui.CTRL_TEXT, 200, 100, 32, gui.OPT_CENTER, "Latutude (deg)"],
            [gui.CTRL_TEXT, 200, 100+y_offset, 32, gui.OPT_CENTER, self.latitude.display_val],
            [gui.CTRL_TEXT, 600, 100, 32, gui.OPT_CENTER, "Longitude (deg)"],
            [gui.CTRL_TEXT, 600, 100+y_offset, 32, gui.OPT_CENTER, self.longitude.display_val],
            [gui.CTRL_TEXT, 200, 300, 32, gui.OPT_CENTER, "Height (m) "],
            [gui.CTRL_TEXT, 200, 300+y_offset, 32, gui.OPT_CENTER, self.height.display_val],
            [gui.CTRL_TEXT, 600, 300, 32, gui.OPT_CENTER, "Speed (mph)"],
            [gui.CTRL_TEXT, 600, 300+y_offset, 32, gui.OPT_CENTER, self.speed.display_val],
            [gui.DL_BEGIN(gui.PRIM_LINES)],
            [gui.DL_VERTEX2F(15, 135)], [gui.DL_VERTEX2F(380, 135)],
            [gui.DL_VERTEX2F(400, 135)], [gui.DL_VERTEX2F(790, 135)],
            [gui.DL_VERTEX2F(55, 335)], [gui.DL_VERTEX2F(325, 335)],
            [gui.DL_VERTEX2F(440, 335)], [gui.DL_VERTEX2F(760, 335)],
        ])
        self.add_button_icons()

    def teardown(self):
        super().teardown()

    def new_data_cb(self):
        self.latitude.update(Application.Data.lat_degE7)
        self.longitude.update(Application.Data.lng_degE7)
        self.height.update(Application.Data.alt_msl_m)
        self.speed.update(Application.Data.speed_ms)


def load_fonts():
    from font import load_font
    path = os.getcwd() + '/'
    start, end = load_font(path + 'BebasNeue_0-184.rft', 10)

    if end < Application.image_bank.end:
        print('RAM_G FULL! images: 0 - 0x{:08X} fonts: 0x{:08X} - 1MB'.format(
            Application.image_bank.end, end))
        print('           over by: 0x{:08X} bytes'.format(Application.image_bank.end - end))


def main():
    path = os.getcwd() + '/'
    vts.catch_callback_exceptions(False)
    Application.image_bank = Image_Bank((
        (path + 'icon-gnss.png',            'GNSS'),
        (path + 'icon-media.png',           'Media'),
        (path + 'icon-record.png',          'Record'),
        # (path + 'icon-exit.png',            'Exit'),
        # (path + 'icon-settings.png',        'Settings'),
        # (path + 'icon-radio.png',           'Radio'),
    ))

    Application.Icons.buttons = [
        Picture_Button(335, -15, Application.image_bank.get('Media'), 'Media', Application.toggle_logging),
        Picture_Button(405, -15, Application.image_bank.get('GNSS'), 'GNSS', default_cb),
        Picture_Button(270, -15, Application.image_bank.get('Record'), 'Record', default_cb, gui.DL_COLOR(Colours.rl_header), gui.DL_COLOR(Colours.rl_header)),
        # Picture_Button(660, 5, Application.image_bank.get('Radio'), 'Radio', default_cb, gui.DL_COLOR(0xFFFFFF)),
        # Picture_Button(-5, 415, Application.image_bank.get('Settings'), 'Settings', default_cb),
        # Picture_Button(0,  410, Application.image_bank.get('Exit'), 'Exit', ScreenManager.switch_to_last_screen),
    ]
    Application.Icons.gnss = Application.Icons.get_picture_button('GNSS')
    Application.Icons.media = Application.Icons.get_picture_button('Media')
    Application.Icons.logging = Application.Icons.get_picture_button('Record')
    # load_fonts()

    # Application.UserSettings.load_from_file()
    # Application.UserSettings.load_from_eeprom()

    set_appinfo('Tunnel Test {}'.format(Application.version))

    while (gnss.init_status() > 0):
        pass
    try:
        vbox.init(vbox.VBOX_SRC_GNSS_BASIC)
    except Exception as e:
        if str(e) == 'VBox source already configured':
            pass
        else:
            raise e


    ########################################################
    # adas_task = Task(calculate_sample, name='adas_task', wake_flag = True)
    # log_task = Task(logging_task, name="log_task", wake_flag = True)
    # Application.add_task(adas_task)
    # Application.add_task(log_task)

    ScreenManager.Add_Screen(MainScreen(), 'Main', start=True)

    while vbox.samples_pending():
        _ = vbox.get_sample_hp() #throw away samples we missed during boot_up, GNSS probably hasn't got first lock yet anyway
    vbox.set_new_data_callback(gnss_cb)

    vts.set_sd_callback(Application.sd_callback)

    # Application.run_loop()

    print("Exit Main")

if __name__ == "__main__":
    main()