import os
import logging
import sys
import time


class LoggerWrapper:

    """
        The following class holds static methods that are used to configure python logger
        to print log prints for log file and stdout.
        In addition, this class has log messages wrapper method, etc.
    """

    @staticmethod
    def init_logger(log_dir_name: str, log_level: str, log_format: str, log_file_name: str):
        """
        Initialize the import script's logger to log to a log file and to stdout.
        """
        if not os.path.exists(log_dir_name):
            os.makedirs(log_dir_name)

        # set log datetime to UTC:
        logging.Formatter.converter = time.gmtime

        # set log level to debug:
        log_levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR}
        log_level = log_levels.get(log_level, logging.DEBUG)
        logging.basicConfig(
            filename=log_file_name,
            format=log_format,
            level=log_level
        )

        # set stdout log level to info:
        console_handler = logging.StreamHandler(stream=sys.stdout)
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(logging.Formatter(log_format))
        logging.getLogger().addHandler(console_handler)

    @staticmethod
    def log_message_wrapper(message_prefix: str, message: str, logger_level='info'):
        """
        The following method is used to log messages in specific logger level.
        This method can accept a message prefix as input and log it before the message (for example s3AccessRequestId, requestId etc).
        """
        log_level = getattr(logging, logger_level.upper(), logging.INFO)
        if message_prefix:
            logging.log(level=log_level, msg=f"{message_prefix} {message}")
        else:
            logging.log(level=log_level, msg=message)

    @staticmethod
    def log_message_elapsed_time(elapsed_time_seconds, message_prefix, message, message_suffix=None, message_log_level="info"):
        """
        Log a message with elapsed time.
        """
        minutes, seconds = divmod(elapsed_time_seconds, 60)
        base_message = f"{message} {int(minutes)} minutes and {int(seconds)} seconds" if minutes >= 1 else f"{message} {int(seconds)} seconds"
        full_message = f"{base_message} {message_suffix}".strip() + "." if message_suffix is not None else base_message + "."
        LoggerWrapper.log_message_wrapper(message_prefix=message_prefix,
                                          message=full_message,
                                          logger_level=message_log_level)

    @staticmethod
    def is_logger_configured():
        """
        Check if the script logger is configured or not.
        """
        return any(handler for handler in logging.getLogger().handlers)
