#! /usr/bin/python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from logging import (
    getLogger,
    ERROR
)
from luma.core.error import DeviceNotFoundError
from os import path
from pathlib import Path
from signal import (
    signal,
    SIGINT,
    SIGTERM
)
from sys import exit

from pitopcommon.logger import PTLogger
from pitopcommon.common_names import DeviceName

from pitop.system.device import device_type
from pitop.miniscreen import Miniscreen

from components.widgets.common.functions import get_image_file_path
from components.MenuManager import MenuManager


boot_animation_played_breadcrumb = "/tmp/.pt-sys-oled.boot-played"
custom_startup_gif_path = "/etc/pi-top/pt-sys-oled/startup.gif"


def configure_interrupt_signals(app):
    def signal_handler(signal, frame):
        PTLogger.debug("Stopping...")
        app.stop()
        PTLogger.debug("Stopped!")
    signal(SIGINT, signal_handler)
    signal(SIGTERM, signal_handler)


def should_run():
    try:
        return device_type() == DeviceName.pi_top_4.value
    except Exception:
        PTLogger.info(
            "Could not determine pi-top hub type from pt-device-manager. Exiting...")
        exit(1)

    PTLogger.info("Not running on a pi-top [4]. Exiting...")
    return False


def get_parser():
    parser = ArgumentParser(description="pi-top OLED sys menu")
    parser.add_argument(
        "--log-level",
        type=int,
        help="set the logging level from 10 (more verbose) to 50 (less verbose)",
        default=20,
    )
    return parser


def main():
    try:
        args = get_parser().parse_args()

        # Ignore PIL debug messages
        getLogger('PIL').setLevel(ERROR)
        PTLogger.setup_logging(logger_name="pt-sys-oled",
                               logging_level=args.log_level,
                               log_to_journal=False)

        if should_run():
            device_found = False
            try:
                miniscreen = Miniscreen()
                device_found = True
            except DeviceNotFoundError as e:
                PTLogger.error(f"Error getting device: {str(e)}")

            # If device is not found, exit normally to avoid restarting the service repeatedly
            if not device_found:
                return

            already_played_boot_animation = path.exists(
                boot_animation_played_breadcrumb)
            if not already_played_boot_animation:
                PTLogger.info("Not played boot animation this session")
                PTLogger.info("Starting startup animation")

                def play_animated_gif(gif_path):
                    miniscreen.play_animated_image_file(
                        gif_path,
                        background=False,
                        loop=False
                    )

                try:
                    play_animated_gif(custom_startup_gif_path)

                except Exception:
                    # Fallback
                    play_animated_gif(
                        get_image_file_path("startup/pi-top_startup.gif")
                    )

                Path(boot_animation_played_breadcrumb).touch()

                PTLogger.info("Finished startup animation")

            PTLogger.info("Setting up application")
            app = MenuManager(miniscreen)
            configure_interrupt_signals(app)
            PTLogger.info("Starting application")
            app.main_loop()
            app.stop()

    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()
