# -*- coding: utf-8 -*-

import connector_util
from fylr_lib_plugin_python3 import util


def easydb_server_start(easydb_context):

    # api callback for url /api/plugin/base/PLUGIN/list
    easydb_context.register_callback(
        'api',
        {
            'name': 'list',
            'callback': 'get_connector_list',
        },
    )
    logger = easydb_context.get_logger(connector_util.PLUGIN_NAME)
    logger.debug(f'registered api /api/plugin/base/{connector_util.PLUGIN_NAME}/list')


def response(body, status_code=200):
    return {
        'headers': {
            'Content-Type': 'application/json; charset: utf-8',
        },
        'status_code': status_code,
        'body': util.dumpjs(body),
    }


def error_response(error, logger, detail=None, status_code=500):
    err = {
        'realm': 'user',
        'code': error,
    }

    if detail:
        err['parameters'] = {
            'detail': detail,
        }

    logger.error(util.dumpjs(err))

    return response(err, status_code)


def get_connector_list(easydb_context, parameters):

    logger = easydb_context.get_logger(connector_util.PLUGIN_NAME)

    try:

        # check the rights of the user to use the connectors
        session = easydb_context.get_session()
        if session is None:
            raise connector_util.NotAuthenticated()

        easydb_context.check_system_right(
            f'plugin.{connector_util.PLUGIN_NAME}.allow_use',
            session,
        )

        config = easydb_context.get_config()

        connectors = connector_util.Connector(
            parameters=parameters,
            session=session,
            base_config=util.get_json_value(config, 'base'),
            plugin_base_config=util.get_json_value(config, 'system.base_config.system'),
            is_fylr=False,
        ).get_connector_list()

        return response(connectors)

    except connector_util.NotAuthenticated as e:
        return error_response(
            'error.user.not_authenticated',
            str(e),
        )

    except connector_util.NotEnabled as e:
        return response(
            {
                'easydbs': [],
            }
        )
