import logging.handlers
import os
from logging import (
    LogRecord,
    Formatter,
)

from sysactions import action

LOGGER_NAME = "ExternalLog_{}.log"
FIVE_MEGABYTES = 5242880

configured_handlers = {}


class NoNewLineFormatter(Formatter):
    def format(
        self,       # type: NoNewLineFormatter
        record,     # type: LogRecord
    ):
        ret = super(NoNewLineFormatter, self).format(record)
        if ret[-1] == '\n':
            return ret[:-1]
        return ret


@action
def external_log(
    pos_id,         # type: str
    message,        # type: str
):
    if pos_id not in configured_handlers:
        _add_rotating_file_handler_to_pos_id(pos_id)

    rotating_file_handler = configured_handlers[pos_id]
    rotating_file_handler.emit(
        _create_dummy_log_record(message=message)
    )


def _add_rotating_file_handler_to_pos_id(
    pos_id,     # type: str
):
    pos_logger_name = LOGGER_NAME.format(pos_id.zfill(2))
    pyscripts_directory = os.path.abspath(os.path.dirname(os.environ["LOADERCFG"]))
    file_name = os.path.join(pyscripts_directory, pos_logger_name)
    handler = logging.handlers.RotatingFileHandler(
        filename=file_name,
        mode='a',
        maxBytes=FIVE_MEGABYTES,
        backupCount=5,
    )
    handler.setFormatter(NoNewLineFormatter())
    configured_handlers[pos_id] = handler


def _create_dummy_log_record(
    message,        # type: str
):
    return LogRecord(
        name="",
        level=logging.DEBUG,
        pathname="",
        lineno=0,
        msg=message,
        args=(),
        exc_info=None,
    )
