import os.path
from PIL import Image, ImageDraw, ImageFont, ImageSequence
from luma.core.virtual import viewport
from luma.core.render import canvas

import Data
import util
import sys
import signal
import OPi.GPIO as GPIO
from demo_opts import get_device
from luma.core.sprite_system import framerate_regulator
import Constants


import time
from threading import Lock, Timer, Thread

from util import construct_luma_core_display_args

loading_gif_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'images/gif', 'loading.gif'))

gif_progress = Image.open(loading_gif_path)

Font1 = ImageFont.truetype(os.path.join(os.path.dirname(__file__), "fonts/FreeSans.ttf"), 12, encoding="unic")
Font2 = ImageFont.truetype(os.path.join(os.path.dirname(__file__), "fonts/FreeSans.ttf"), 11, encoding="unic")
Font3 = ImageFont.truetype(os.path.join(os.path.dirname(__file__), "fonts/FreeSans.ttf"), 10, encoding="unic")
Font4 = ImageFont.truetype(os.path.join(os.path.dirname(__file__), "fonts/FreeSans.ttf"), 9, encoding="unic")
Font5 = ImageFont.truetype(os.path.join(os.path.dirname(__file__), "fonts/FreeSans.ttf"), 8, encoding="unic")

class Display:
    device = get_device(construct_luma_core_display_args())
    virtual = viewport(device, width=128, height=128)


def create_screen_home_page():
    with canvas(Display.virtual) as draw:
        draw.line(Constants.HOME_SCREEN_LINE_0, fill="white")
        draw.text(Constants.HOME_SCREEN_POS_0, "STATUS", fill="white", font=Font2)
        draw.text(Constants.HOME_SCREEN_POS_1, "HOME", fill="white", font=Font1)

def print_oled(text):
    print(str(text))
    with canvas(Display.virtual) as draw:
        draw.text((15, 51), str(text), fill="white", font=Font2)

def create_black_screen():
    with canvas(Display.virtual) as draw:
        draw.rectangle(Constants.BLACK_SCREEN_POS, fill="black")

def loading():
    regulator = framerate_regulator(fps=10)
    background = Image.new("RGB", Display.device.size, "black")
    test = 100
    while test > 0:
        for frame in ImageSequence.Iterator(gif_progress):
            with regulator:
                background.paste(frame.resize((100, 100), resample=Image.BILINEAR), (13, 0))
                draw = ImageDraw.Draw(background)
                draw.text((15, 101), "Update in progress...", fill="white", font=Font3)
                Display.device.display(background.convert(Display.device.mode))
        test += 1
    return

def updateDsp():
    regulator = framerate_regulator(fps=10)
    background = Image.new("RGB", Display.device.size, "black")
    test = 100
    while test > 0:
        for frame in ImageSequence.Iterator(gif_progress):
            with regulator:
                background.paste(frame.resize((100, 100), resample=Image.BILINEAR), (13, 0))
                draw = ImageDraw.Draw(background)
                draw.text((25, 101), "Update DSP(s) ...", fill="white", font=Font3)
                Display.device.display(background.convert(Display.device.mode))
        test += 1
    return

def do_nothing(obj):
    pass

def handler(signum, frame):
    create_black_screen()
    time.sleep(1)
    sys.exit()

def main():
    signal.signal(signal.SIGINT, handler)
    GPIO.setwarnings(False)
    util.update_board_revision()
    display = Display()
    Display.device.cleanup = do_nothing
    if (sys.argv[1] == "blank"):
        create_black_screen()
    elif (sys.argv[1] == "test"):
        create_screen_home_page()
    elif (sys.argv[1] == "print"):
        print_oled(sys.argv[2])
    elif (sys.argv[1] == "load"):
        loading()
    elif (sys.argv[1] == "updatedsp"):
        updateDsp()
    else :
        print("wrong argument")



if __name__ == "__main__":
    main()