#!/bin/python3

import sys

from fylr_lib_plugin_python3 import util
import connector_util


if __name__ == '__main__':

    if len(sys.argv) < 2:
        util.return_error_response('parameter missing: "info.json"')

    # get token from info
    info_json, error = connector_util.load_json(sys.argv[1])
    if error:
        util.return_error_response(
            f'invalid parameter: "info.json" can not be parsed as JSON: {error}'
        )

    token = util.get_json_value(info_json, 'api_user_access_token')

    # api_url
    api_url = util.get_json_value(info_json, 'api_url')

    # get session from api
    session, error = connector_util.Connector.easydb_get(
        api_url,
        'user/session',
        url_params={
            'access_token': token,
        },
    )
    if error:
        util.return_error_response(util.dumpjs(error))

    try:
        # check if this user is allowed to use the connector
        connector_util.check_connector_use_right(session)

        response = connector_util.Connector(
            parameters=util.get_json_value(info_json, 'request'),
            session=session,
            base_config=util.get_json_value(info_json, 'config'),
            plugin_base_config=util.get_json_value(
                info_json, 'plugin.manifest.BaseConfig'
            ),
            is_fylr=True,
        ).get_connector_list()

        util.return_response(response)

    except connector_util.NotAuthenticated as e:
        util.return_response(connector_util.format_error_response(str(e)))

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

    except connector_util.NoSystemRight as e:
        util.return_response(
            connector_util.format_error_response(
                str(e),
                {
                    'right': e.get_right(),
                },
            )
        )

    except Exception as e:
        util.return_error_response(str(e))
