import os
import inspect
from fastapi import FastAPI

__author__ = "Tiago Prata"
__copyright__ = "Copyright 2022, ABB Automacao Ltda (Brazil)"
__credits__ = ["ABB Automacao Ltda", "Tiago Prata"]
__license__ = "Copyright"
__version__ = "1.0.0"
__maintainer__ = "AssetVista Team"
__email__ = "BR-assetvista@abb.com"
__status__ = "Development (do not use in production)"

# TODO: Add comments to classes and functions
# TODO: Create test script
# TODO: Replace prints by logs

AMS_FOLDER_NAME = 'assetmonitors'
REQUIRED_FILES_IN_AM_FOLDER = ['_am_def.py', '_cond_def.py', 'router.py']


def _is_valid_am_folder(folder):
    ''' Verify if the AM folder contains the minimum files requirements to be an Asset Monitor folder
    '''
    required_files = REQUIRED_FILES_IN_AM_FOLDER.copy()

    if not folder.is_dir(): print(''.join(['Asset Monitor path (', folder.name, ') is not a folder'])); return False

    for subitem in os.listdir(folder):
        if os.path.isfile(os.path.join(folder, subitem)):
            if subitem in required_files:
                required_files.pop(subitem)
                print(''.join(['Requirement ', subitem, ' found on Asset Monitor folder']))

    if len(required_files) == 0:
        print(''.join(['All required files found on ', folder]))
        return True
    else:
        print(''.join(['Missing required files on folder ', folder]))
        print('Missing files:')
        print(required_files)
        return False



def _get_ams_list(folders_to_be_ignored = [], assetmonitors_folder_path = None):

    if assetmonitors_folder_path == None:
        # get the path of the file that called this module
        frame = inspect.stack()[1]
        module = inspect.getmodule(frame[0])
        filename = module.__file__
        app_folder = os.path.dirname(os.path.realpath(filename))
        ams_folder = os.path.join(app_folder, AMS_FOLDER_NAME)
    else:
        ams_folder = os.path.join(assetmonitors_folder_path)

    subfolders = []
    for folder in os.scandir(ams_folder):
        if not folder.is_dir(): print(''.join(['Asset Monitor path (', folder.name, ') is not a folder'])); continue
        if folder.name in folders_to_be_ignored: print(''.join(['Folder ', folder.name, ' marked to be ignored.'])); continue
        if folder.name.startswith('__'): print(''.join(['Folder ', folder.name, ' ignored because it starts with dunder (__)'])); continue
        if folder.name.startswith('.'): print(''.join(['Folder ', folder.name, ' ignored because it starts with dor (.)'])); continue
        if not _is_valid_am_folder(folder): print('Invalid AM folder!')

        subfolders.append(folder.name)

    return subfolders


def _include_am_routers(fastapi_app: FastAPI, ams_list):

    # Importing AMs libs
    for am in ams_list:
        import_str = ''.join(['from ', AMS_FOLDER_NAME, '.', am, ' import router as ', am])
        print(''.join(['Importing: ', import_str]))
        exec(import_str)

    # Including routers
    for am in ams_list:
        router = eval(''.join([am, '.router']))
        fastapi_app.include_router(router)

    return fastapi_app


def add_assetvista_routes(fastapi_app: FastAPI, folders_to_be_ignored = []):
    ams_list = _get_ams_list(folders_to_be_ignored)
    return _include_am_routers(fastapi_app, ams_list)