import display
import buttons
import sys
import mch22
import gc

_SKIP_INTRO = False

APP_PATH = "/".join(__file__.split("/")[:-1])

# Add Application path to sys path to import modules as if they were root modules
sys.path.append(APP_PATH)
import main
import utils


def draw_intro(font):
    text = "Press START To Continue"
    text_width = display.getTextWidth(text, font)
    display_size = display.size()

    display.drawFill(0)
    display.flush()

    max_frame = 30
    frame = 0
    png_width = 200
    offset = (display_size[0] - png_width) // 2
    while frame <= max_frame:
        if _SKIP_INTRO or buttons.value(buttons.BTN_START):
            break
        display.drawFill(0)
        display.drawPng(offset, 0, "%s/intro%02d.png" % (APP_PATH, frame))
        display.drawText(
            (display_size[0] - text_width) // 2,
            222,
            text,
            utils.TEXT_HIGHLIGHT,
            font,
        )
        display.flush()
        frame += 1


def _skip_intro(pressed):
    global _SKIP_INTRO
    if pressed:
        _SKIP_INTRO = True
        gc.collect()
        buttons.detach(buttons.BTN_START)
        main.main_menu()


def intro():
    global _SKIP_INTRO
    _SKIP_INTRO = False
    buttons.attach(buttons.BTN_START, _skip_intro)
    draw_intro(utils.ARCADE_FONT[8])


def button_exit_app(pressed):
    if pressed:
        mch22.exit_python()

gc.threshold(gc.mem_free() // 2)
buttons.attach(buttons.BTN_HOME, button_exit_app)
intro()
