# -*- coding: utf-8 -*-
"""Define LRM logging."""

import json
import logging.config
import pathlib
import typing


def init_lrm_logging(folder: str, name: str, is_web: bool, instance: int):
    instance_str = "" if instance <= 0 else f"{instance}"

    config_exists = True
    if pathlib.Path("Logging.cfg").exists():
        try:
            with open("Logging.cfg", "rb") as fp:
                config_dict = json.load(fp)
        except json.decoder.JSONDecodeError as err:
            print(f"Error while reading logging.cfg: {err.msg}/nUsing default logging.")
            config_exists = False
    else:
        config_exists = False

    if config_exists:
        if name:
            web_str = "web_" if is_web else ""
            # ensure folder exists and set
            path = pathlib.Path(folder).joinpath(f"{web_str}{name}{instance_str}.log")
            path.parent.mkdir(exist_ok=True)
            config_dict["handlers"]["to_file"]["filename"] = str(path)
    else:
        config_dict = {
            "version": 1,
            "disable_existing_loggers": True,
            "formatters": {
                "standard": {
                    "format": "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
                },
            },
            "handlers": {
                "default": {
                    "level": "INFO",
                    "formatter": "standard",
                    "class": "logging.StreamHandler",
                    "stream": "ext://sys.stdout",
                },
            },
            "loggers": {
                "": {  # root logger
                    "handlers": ["default"],
                    "level": "INFO",
                    "propagate": False
                },
            }
        }

    logging.config.dictConfig(config_dict)

    return logging.getLogger(f"{name}{instance_str}")


lrm_log: typing.Optional[logging.Logger] = init_lrm_logging("C:\\Users\\U5Q80PK\\Desktop\\TCI_Diplomka\\Diplomka\\LrmLogging.py", "results", False, 2)
