import os
import json
import logging
from logging import Logger

from helper import config_logger
from typing import Optional

COMPONENT_NAME = "nperipherals"


def configure_logger(component_name, service_name=None, root_level=logging.DEBUG):
    # type: (str, Optional[str], int) -> Logger

    log_path = os.environ["LOG_PATH"]

    if os.path.isfile(log_path) and log_path.endswith(".json"):
        log_path = _update_log_name(component_name, service_name, log_path)

    config_logger(log_path, component_name, root_level=root_level, max_files=10, max_size=10485760)
    return logging.getLogger(component_name)


def _update_log_name(component_name, service_name, log_path):
    # type: (str, str, str) -> str

    with open(log_path, "rb") as f:
        log_config = json.loads(f.read().decode("utf-8"))
        file_name = log_config.get("handlers", {}).get("default", {}).get("filename", None)

        if not file_name or "$SERVICE_NAME" not in file_name:
            return log_path

        log_name = "{}_{}".format(component_name, service_name) if service_name else component_name
        file_name = file_name.replace("$SERVICE_NAME", log_name)
        log_config["handlers"]["default"]["filename"] = file_name
        log_path = log_config

    return log_path
