import dataiku

from graph.connections.neo4j.preset import Neo4jPresetConfig
from graph.exploration.queries.neo4j.list_databases import list_databases as list_neo4j_databases


def do(payload, config, plugin_config, inputs):
    client = dataiku.api_client()
    parameter_name = payload["parameterName"]
    

    if parameter_name == "db_explorer_folder_paths":
        client = dataiku.api_client()
        project = client.get_project(dataiku.get_custom_variables()["projectKey"])
        managed_folders = project.list_managed_folders()
        choices = [{"value": folder["name"], "label": folder["name"]} for folder in managed_folders]
        return {"choices": choices}
    elif parameter_name == "neo4j_external_databases":
        neo4j_configuration = config.get("neo4j_configuration")
        if neo4j_configuration:
            neo4j_configuration = Neo4jPresetConfig.from_dict(neo4j_configuration)
        else:
            return {"choices": []}

        database_names = list_neo4j_databases(
            uri=neo4j_configuration.neo4j_uri,
            username=neo4j_configuration.neo4j_username,
            password=neo4j_configuration.get_neo4j_password(),
        )
        return {"choices": [{"value": p, "label": p} for p in sorted(list(database_names))]}
    else:
        raise Exception(f"Unexpected parameter name '{parameter_name}'.")
