import os
import logging
import logging.config
from tlib.base import TestHelper


def get_tlib_logger(request):
    """
    Returns logger named tlib.\n
    This logger should only be used by TLib modules. To log from a test or test module use get_test_logger\n
    Logger will get flushed at the end to ensure data is not lost if tests exits abnormally
        """
    return get_logger(request, "tlib")


def get_adb_logger(request):
    """
    Returns logger named adb.\n
    This logger should only be used by adb modules. To log from a test or test module use get_test_logger\n
    Logger will get flushed at the end to ensure data is not lost if tests exits abnormally
        """
    return get_logger(request, "adb")

def get_test_logger(request):
    """
    Returns logger named test.\n
    This logger should only be used by test modules. To log from a test or test module use get_test_logger\n
    Logger will get flushed at the end to ensure data is not lost if tests exits abnormally
    """
    return get_logger(request, "test")

def get_logger(request, logger):
    """
    Returns a logger that has a console and a file handler.\n

    @param logger: Logger name to return
    @type logger: str
    @return:
    """
    #Get current folder
    config_folder = TestHelper.tlib_config_folder()
    try:
        logging.config.fileConfig(os.path.join(config_folder, "logging.conf"))
    except IOError:
        raise IOError("Couldn't create logger object. Make sure log folder exists and you have write permissions")

    logger = logging.getLogger(logger)

    # Create a file handler
    curr_folder = os.path.dirname(request.fspath.strpath)

    #Go up to three levels to find log folder
    log_folder = None
    for i in range(1, 4):
        curr_folder = os.path.abspath(os.path.join(curr_folder, os.pardir))

        #Check if there is a folder 'screenshots'
        folder = os.path.join(curr_folder, 'logs')
        if os.path.exists(folder):
            log_folder = folder
            break

    if log_folder is None:
        raise IOError("Couldn't find logs folder. Create it under your project and try again")

    formatter = logger.handlers[0].formatter

    fh = logging.FileHandler(os.path.join(log_folder, 'test.log'))
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)

    logger.addHandler(fh)

    return logger