##
# @file      main_sd.py
# @brief     Image display and transition
# @version   1.0
#

import ft8xx as ft
import gc
import gui
from utils import Colors, read_csv
import vts
import os

img1 = False

def load_img(fn,ptr):
    with open(fn, 'rb') as f:
        img = f.read()
    gui.pause(True)
    ram_dl0 = ft.rd32(ft.REG_CMD_DL) - 4
    ft.cpcmd_loadimage(ptr, 0, len(img), ft.addressof(img))
    ram_dl1 = ft.rd32(ft.REG_CMD_DL)
    img_display = []
    for i in range((ram_dl1 - ram_dl0) // 4):
        img_display.append(ft.rd32(ft.RAM_DL + ram_dl0 + i * 4))
    # print([hex(x) for x in img_display])
    gui.pause(False)
    return img_display

def vsync_cb(l):
    global closing_alpha_num, flag_end
    if closing_alpha_num < 60:
        closing_alpha_num += 1
        closing_alpha[0] = gui.DL_COLOR_A(int((closing_alpha_num ** 2) * (255/3600)))
        gui.redraw()
    else:
        closing_alpha[0] = gui.DL_COLOR_A(255)
        flag_end = True

def closing_screen(pic1,pic2):
    global closing_alpha, closing_alpha_num, flag_end, logo, img1
    closing_alpha_num = 0
    closing_alpha = [gui.DL_COLOR_A(closing_alpha_num)]
    flag_end = False
    gui.show([
        [gui.EVT_VSYNC, vsync_cb],
        # Gradient
        [0xffffff0b, 0, Colors.gradblue0, (480 << 16) | 200, Colors.gradblue1],
        [gui.DL_COLOR(Colors.white)],
        closing_alpha,
        pic1,
        [gui.PRIM_BITMAPS, [gui.DL_VERTEX2F(0, 0)]],
    ])
    while not flag_end:
        pass

    vts.delay_ms(10000)

    closing_alpha_num = 0
    closing_alpha = [gui.DL_COLOR_A(closing_alpha_num)]
    flag_end = False
    gui.show([
        [gui.EVT_VSYNC, vsync_cb],
        # Gradient
        [0xffffff0b, 0, Colors.gradblue0, (480 << 16) | 200, Colors.gradblue1],
        [gui.DL_COLOR(Colors.white)],
        pic2,
        [gui.PRIM_BITMAPS, [gui.DL_VERTEX2F(0, 0)]],
        [gui.DL_COLOR(Colors.black)],
        closing_alpha,
        [gui.PRIM_RECTS, [gui.DL_VERTEX2F(0, 0), gui.DL_VERTEX2F(800, 480)]],
    ])
    while not flag_end:
        pass

    if img1:
        logo = load_img('VBOX.png',0x10000)
        print("Loaded Image VBOX")
        img1 = False
    else:
        logo = load_img('VBOX2.png',0x10000)
        print("Loaded Image VBOX2")
        img1 = True

# Silence whiny speaker. Playing sounds later will require setting bit 1 of
# REG_GPIOX first.
ft.wr16(ft.REG_GPIOX, 0x80)

gui.show([
    [gui.PARAM_CLRCOLOR, 0],
    [gui.CTRL_TEXT, 400, 240, 30, gui.OPT_CENTER, 'Loading...'],
])


global logo
logo = load_img('VBOX.png',0x10000)
print("Loaded Image VBOX")

vts.leds(*[0]*12)
while True:
    gui.show([
        # Gradient
        [0xffffff0b, 0, Colors.gradblue0, (480 << 16) | 200, Colors.gradblue1],
    ])
    closing_screen(logo,logo)
    print("Finished Transition")
