"""エントリーポイント"""

import logging
import logging.handlers
import os
import sys

if hasattr(sys, "_MEIPASS"):
    os.environ["KIVY_NO_CONSOLELOG"] = "1"

from kivy.config import Config

Config.set("graphics", "width", 1280)
Config.set("graphics", "height", 720)
Config.set("graphics", "minimum_width", 1280)
Config.set("graphics", "minimum_height", 720)
Config.set("graphics", "resizable", True)
Config.set("input", "mouse", "mouse, disable_multitouch")
Config.set("kivy", "exit_on_escape", "0")
# Config.set("modules", "showborder", "")

import kivy  # noqa
import kivy.resources  # noqa
from kivy.app import App  # noqa
from kivy.core.text import DEFAULT_FONT, LabelBase  # noqa

import constants  # noqa
import helper  # noqa
import psutil  # noqa
import root_widget  # noqa
from shared_vars import SharedVars  # noqa


class MainApp(App):
    use_kivy_settings = False

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        kivy.resources.resource_add_path(helper.get_resource_path("VLGothic"))
        kivy.resources.resource_add_path(helper.get_resource_path("images"))

        LabelBase.register(DEFAULT_FONT, "VL-PGothic-Regular.ttf")

        self.title = constants.PRODUCT_NAME
        self.icon = "favicon.ico"

        self._logger: logging.Logger = self._initialize_logger()
        self._shared_vars: SharedVars = SharedVars()

    def build(self):
        process: psutil.Process = psutil.Process(os.getpid())
        root = root_widget.RootWidget(self._logger, self._shared_vars, process)
        return root

    def on_stop(self):
        """アプリを終了したとき。"""

        if self._shared_vars.sub_thread_is_running:
            self._shared_vars.is_abort = True

        self._logger.info("======== アプリを終了しました ========")

    def _initialize_logger(self) -> logging.Logger:
        """logging.Logger のインスタンスを作成し、初期設定して返す。

        Returns:
            logging.Logger: 初期設定された logging.Logger のインスタンス。
        """

        os.makedirs(constants.LOG_DIR_PATH, exist_ok=True)

        logger: logging.Logger = logging.getLogger(__name__)
        logger.setLevel(logging.INFO)

        file_handler = logging.handlers.RotatingFileHandler(
            f"{constants.LOG_DIR_PATH}/{constants.FILE_NAME}.log",
            encoding="utf-8",
            maxBytes=1_048_576,
            backupCount=10,
        )
        format: str = "%(asctime)s [%(levelname)s] %(message)s"
        file_handler.setFormatter(logging.Formatter(format))
        logger.addHandler(file_handler)

        logger.info(f"========「{constants.PRODUCT_NAME}」を起動しました ========")
        logger.info(constants.VERSION)
        logger.info(constants.COPYRIGHT)

        return logger


if __name__ == "__main__":
    MainApp().run()
