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

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", 800)
Config.set("graphics", "height", 600)
Config.set("graphics", "minimum_width", 800)
Config.set("graphics", "minimum_height", 600)
Config.set("graphics", "resizable", False)
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 root_widget  # noqa
from shared_vars import SharedVars  # noqa

# フォントの設定
kivy.resources.resource_add_path(helper.get_resource_path("VLGothic"))
LabelBase.register(DEFAULT_FONT, "VL-PGothic-Regular.ttf")


class MainApp(App):
    use_kivy_settings = False

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

        self.title = constants.PRODUCT_NAME
        self.icon = helper.get_resource_path("images/favicon.ico")

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

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

    def build(self):
        root = root_widget.RootWidget(self._logger, self._shared_vars)
        return root

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

        if self._shared_vars.is_subthread_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__":
    # pattern = re.compile(r"(\d+)～(\d+)")
    # m = re.search(pattern, "1～2番地・3～4番地")
    # print(len(m.group()))  # type: ignore
    # print(m.group())  # type: ignore
    MainApp().run()
