#! /usr/bin/env python
__author__ = "Ben Raanan"
__copyright__ = "Copyright 2021, MBARI"
__credits__ = ["MBARI"]
__license__ = "GPL-3.0"
__maintainer__ = "Ben Raanan"
__email__ = "byraanan at mbari.org"
__doc__ = '''

Defines the LRAUV backseat helper service logging functions.

@author: __author__
@license: __license__
'''
import sys
import os
import logging
import time
from datetime import datetime


"""
    
    Create a named global logger.
    
"""


def create_log_base(path_base=os.path.realpath('.')):
    """
    Create a log folder at `/path/to/backseat_app/logs`.

    Folder name format is UTC `YYYYmmddTHHMMSS`.

    :param path_base: string, project path
    :return: string, path log dir
    """
    path_base += '/logs/'
    log_name = datetime.utcnow().strftime('%Y%m%dT%H%M%S')
    log_path = os.path.join(path_base, log_name)
    print("Creating log folder at: {0}.".format(log_path))
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    return log_path


def configure_logger(name='backseat', log_to_file=True):
    """
    Configure and launch logger handlers.

    :param name: string, logger handler name
    :param log_to_file: create and configure the syslog file log handler
    :return: tuple, (logger obj, log path)
    """
    print("Initializing logger with name: '{0}'.".format(name))

    # Configure the log format
    log_format = logging.Formatter('%(asctime)s [%(module)s](%(levelname)s): %(message)s')

    # Create and configure the console log handler
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_format)
    logging.Formatter.converter = time.gmtime
    console_handler.setLevel(logging.INFO)

    log_path = None
    file_handler = None
    if log_to_file:
        # Create a new log folder
        log_path = create_log_base()
        # Create and configure the syslog file log handler
        file_handler = logging.FileHandler("{0}/syslog".format(log_path))
        file_handler.setFormatter(log_format)
        file_handler.setLevel(logging.DEBUG)

    # Create the the root logger...
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False
    # ...and add the console/file handlers
    logger.addHandler(console_handler)
    if log_to_file:
        logger.addHandler(file_handler)

    # Redirect uncaught exception messages to the logger (and log them to file)
    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

    sys.excepthook = handle_exception

    return logger, log_path
