from typing import Any, Dict, Optional

import dataiku
from dataiku.customrecipe import get_recipe_config
from dataiku.customwebapp import get_webapp_config


class DataikuApi:
    def __init__(self):
        self._webapp_config: Dict = {}
        self._default_project = None
        self._default_project_key: Optional[str] = None
        self._client = dataiku.api_client()

    def setup(self, webapp_config: Dict, default_project_key: str):
        self._webapp_config = webapp_config
        self._default_project_key = default_project_key

    @property
    def client(self):
        if self._client is None:
            raise Exception("Please set the client before using it.")
        else:
            return self._client

    @client.setter
    def client(self, c: Any):
        raise Exception(
            "If working outside of Dataiku, Client can only be set through the function setup()"
        )

    @property
    def default_project(self):
        try:
            return self.client.get_default_project()
        except Exception:
            if self._default_project_key:
                return self.client.get_project(self._default_project_key)
            else:
                raise Exception(
                    "Please define the default project before using it.")

    @property
    def default_project_key(self):
        try:
            return dataiku.get_custom_variables()["projectKey"]
        except Exception:
            if self._default_project_key:
                return self._default_project_key
            else:
                raise Exception(
                    "Please define the default project before using it.")

    @property
    def webapp_config(self) -> Dict[str, str]:
        try:
            self._webapp_config = get_webapp_config()
            return self._webapp_config
        except Exception:
            return self._webapp_config

    @property
    def recipe_config(self):
        try:
            self._recipe_config = get_recipe_config()
            return self._recipe_config
        except Exception:
            return self._recipe_config

    def __str__(self):
        return (
            f"_webapp_config: {self._webapp_config}, "
            f"_default_project: {self._default_project}, "
            f"_default_project_key: {self._default_project_key}, "
            f"_client: {self._client}"
        )


dataiku_api = DataikuApi()
