# init.py -- Pamhyr
# Copyright (C) 2023-2026  INRAE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import sys
import os
import locale
import logging

from PyQt5.QtCore import QTranslator, QLibraryInfo

from tools import (
    reset_timers, display_timers, timer,
    logger_color_blue, logger_color_red, logger_color_green, logger_color_reset
)
from config import Config

from View.MainWindow import ApplicationWindow
from Model.Study import Study


# Configure logger

logging.basicConfig(
    level=logging.DEBUG,
    format=(f'[{logger_color_blue()}PAMHYR{logger_color_reset()}]' +
            f'[{logger_color_green()}%(levelname)s{logger_color_reset()}]' +
            ' %(message)s')
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    log = os.path.join(
        os.path.dirname(Config.filename()), "log.txt"
    )
    logfile = open(log, "w+", encoding="utf-8")
    handler = logging.StreamHandler(logfile)
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
    handler.setFormatter(formatter)
    handler.setLevel(logging.DEBUG)
    logger.addHandler(handler)
except Exception as e:
    logger.error(f"Failed to create logfile... {e}")


def legal_info():
    "Display in stdout Pamhyr infomation about licence and version"
    def blue(s): return logger.info(
        f"{logger_color_blue()}{s}{logger_color_reset()}")

    with open(os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                "motd.txt"
            )
    ), "r", encoding="utf-8") as f:
        for line in f:
            print(line.rstrip())

    with open(os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                "VERSION"
            )
    ), "r", encoding="utf-8") as f:
        version = f.readline().strip()
        logger.info(
            f"version:  {logger_color_green()}{version}{logger_color_reset()}")

    logger.info("license: pamhyr  Copyright (C) 2023-2026  INRAE")
    logger.info("license: This program comes with ABSOLUTELY NO WARRANTY.")
    logger.info(
        "license: This is free software," +
        " and you are welcome to redistribute it"
    )
    logger.info("license: under certain conditions.")


def debug_info():
    py_version = sys.version.split("\n")[0]
    logger.debug(f"python: {py_version}")

    info = QLibraryInfo
    logger.debug(f"Qt PrefixPath: {info.location(QLibraryInfo.PrefixPath)}")
    logger.debug(
        "Qt LibExecPath: " +
        f"{info.location(QLibraryInfo.LibraryExecutablesPath)}"
    )


def setup_lang(app, conf: Config):
    "Return QTranslator configured for current language"
    lang_file = ""
    translator = QTranslator()

    if conf.lang == "":
        # System language
        sys_lang = locale.getdefaultlocale()
        if "fr" in sys_lang[0]:
            lang_file = os.path.dirname(__file__) + "/lang/fr.qm"
    elif conf.lang == "fr":
        # French
        lang_file = os.path.dirname(__file__) + "/lang/fr.qm"
    else:
        # English default language
        lang_file = ""

    if lang_file != "":
        logger.info(f"Load lang file: {lang_file}")
        ok = translator.load(lang_file)
        if not ok:
            logger.error("Failed to load translate file")

    return translator
