from datetime import datetime
from functools import wraps
import platform
from time import gmtime, strftime
import logging
import os
from pathlib import Path

LOGS_PATH = os.path.join(Path(__file__).parents[1], "logs")
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(f'{LOGS_PATH}/monitor.log')
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
logger.addHandler(stream_handler)


def logging_endpoint(func):
    @wraps(func)
    def decorated(*args, **kwargs):

        log_mapper = LogMapper()
        tag = 'START'
        log = log_mapper.compose_log(method=func.__name__, message='Trying to connect!', tag=tag)
        logger.info(log)

        response = func(*args, **kwargs)
        log_type = response[1]

        if log_type == 200:
            tag = 'END'
            log = log_mapper.compose_log(method=func.__name__, message='Successful connection!', tag=tag)
            logger.info(log)
        else:
            log = log_mapper.compose_log(method=func.__name__, message='Error connecting!', tag='ABORTED')
            logger.error(log)

        return response

    return decorated


# def logging_method(func):
#     @wraps(func)
#     def decorated(*args, **kwargs):
#
#         log_mapper = LogMapper()
#         tag = 'START'
#         log = log_mapper.compose_log(method=func.__name__, tag=tag)
#         logger.info(log)
#
#         response = func(*args, **kwargs)
#
#         if response:
#             tag = 'END'
#             log = log_mapper.compose_log(method=func.__name__, tag=tag)
#             logger.info(log)
#         else:
#             log = log_mapper.compose_log(method=func.__name__, tag='ABORTED')
#             logger.error(log)
#
#         return response
#     return decorated


class LogMapper:

    @staticmethod
    def get_date():
        date = strftime(f"%Y-%m-%d %H:%M:%S.{datetime.now().microsecond}", gmtime())
        return datetime.strptime(date, "%Y-%m-%d %H:%M:%S.%f")

    @staticmethod
    def get_hostname():
        # TODO: Fix, if run over kubernetes get container name, not host machine
        return platform.node()

    @staticmethod
    def get_service():
        return platform.node().split('-')[0]

    @staticmethod
    def compose_log(method=None, message=None, tag=None):
        log = '[MONITOR] {date} {hostname} {service} {method} {tag} {message}'.format(date=LogMapper.get_date(),
                                                                                      hostname=LogMapper.get_hostname(),
                                                                                      service=LogMapper.get_service(),
                                                                                      method=method,
                                                                                      tag=tag,
                                                                                      message=message)
        return log
