# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/classes/50_DomoJupyter.ipynb.

# %% auto 0
__all__ = ['DomoJupyter_Workspace_Dataset', 'DomoJupyter_Workspace_Account', 'DomoJupyter_Workspace', 'DomoJupyter_Content',
           'DomoJupyter']

# %% ../../nbs/classes/50_DomoJupyter.ipynb 2
import os
import json

from dataclasses import dataclass, field
from typing import Union, List
import datetime as dt
import domolibrary.utils.DictDot as util_dd

from dateutil.parser import parse
import httpx

import domolibrary.client.DomoAuth as dmda
import domolibrary.routes.jupyter as jupyter_routes

# import domolibrary.client.DomoError as de
# import domolibrary.utils.chunk_execution as ce

from nbdev.showdoc import patch_to

# %% ../../nbs/classes/50_DomoJupyter.ipynb 5
# @dataclass
# class Instance:
#     started: str
#     lastActivity: str
#     url: str
#     status: str
#     userId: int


@dataclass
class DomoJupyter_Workspace_Dataset:
    datasource_id: str
    alias: str

    @classmethod
    def _from_json(cls, obj):
        return cls(datasource_id=obj["dataSourceId"], alias=obj["alias"])

    def to_json(self):
        return {"dataSourceId": self.datasource_id, "alias": self.alias}


@dataclass
class DomoJupyter_Workspace_Account:
    account_id: str
    alias: str

    @classmethod
    def _from_json(cls, obj):
        return cls(account_id=obj["account_id"], alias=obj["alias"])

    def to_json(self):
        return {"account_id": self.account_id, "alias": self.alias}


@dataclass
class DomoJupyter_Workspace:
    auth: dmda.DomoAuth = field(repr=False)
    id: str
    name: str
    owner: int  # theoretically Domo supports group ownership however the API does not model this properly
    description: str = None

    jupyter_kernel: str = None

    created: dt.datetime = None
    updated: dt.datetime = None
    last_run: dt.datetime = None

    # instances: List[Instance]
    input_configuration: List[DomoJupyter_Workspace_Dataset] = None
    output_configuration: List[DomoJupyter_Workspace_Dataset] = None
    account_configuration: List[DomoJupyter_Workspace_Account] = None

    co_owners: List[int] = None

    # bootstrap_kernel: bool
    # migrate_files: bool

    cpu: int = 1
    memory: int = 8
    sharing_enabled: bool = True

    timeout_hours: int = 8

    # sharing_enabled_by: int = None
    # sharing_enabled_date: dt.datetime = None

    # collection_configuration: List
    # fileshare_configuration: List

    @classmethod
    def _from_json(cls, obj: str, auth: dmda.DomoAuth):
        # Convert nested lists of dictionaries to lists of dataclass instances

        return cls(
            auth=auth,
            id=obj.get("id"),
            name=obj.get("name"),
            description=obj.get("description"),
            jupyter_kernel=obj.get("jupyterKernel"),
            created=parse(obj.get("created")),
            updated=parse(obj.get("updated")),
            last_run=parse(obj.get("lastRun")),
            input_configuration=[
                DomoJupyter_Workspace_Dataset._from_json(ds)
                for ds in obj.get("inputConfiguration", [])
            ],
            output_configuration=[
                DomoJupyter_Workspace_Dataset._from_json(ds)
                for ds in obj.get("outputConfiguration", [])
            ],
            account_configuration=[
                DomoJupyter_Workspace_Account._from_json(acc)
                for acc in obj.get("accountConfiguration", [])
            ],
            owner=obj.get("owner"),
            co_owners=obj.get("coOwners"),
            cpu=obj.get("cpu"),
            memory=obj.get("memory"),
            sharing_enabled=obj.get("sharingEnabled"),
            timeout_hours=obj.get("timeoutHours"),
        )

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "owner": self.owner,
            "description": self.description,
            "jupyterKernel": self.jupyter_kernel,
            # "created": self.created,
            # "updated": self.updated,
            # "lastRun": self.last_run,
            "inputConfiguration": [
                dataset.to_json() for dataset in self.input_configuration
            ]
            if self.input_configuration
            else None,
            "outputConfiguration": [
                dataset.to_json() for dataset in self.output_configuration
            ]
            if self.output_configuration
            else None,
            "accountConfiguration": [
                account.to_json() for account in self.account_configuration
            ]
            if self.account_configuration
            else None,
            "coOwners": self.co_owners,
            "cpu": self.cpu,
            "memory": self.memory,
            "sharingEnabled": self.sharing_enabled,
            "timeoutHours": self.timeout_hours,
        }

# %% ../../nbs/classes/50_DomoJupyter.ipynb 6
@patch_to(DomoJupyter_Workspace, cls_method=True)
async def get_by_id(
    cls: DomoJupyter_Workspace,
    auth: dmda.DomoJupyterAuth,
    workspace_id: str,
    return_raw: bool = False,
    debug_api: bool = False,
    debug_num_stacks_to_drop=1,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
):
    res = await jupyter_routes.get_jupyter_workspace_by_id(
        auth=auth,
        workspace_id=workspace_id,
        debug_api=debug_api,
        debug_num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=cls.__name__,
        session=session,
    )

    if return_raw:
        return res

    return cls._from_json(res.response, auth)

# %% ../../nbs/classes/50_DomoJupyter.ipynb 10
@patch_to(DomoJupyter_Workspace)
async def update_config(
    self :DomoJupyter_Workspace,
    debug_api: bool = False,
    debug_num_stacks_to_drop=1,
    parent_class: str = None,
    session : httpx.AsyncClient = None
):

    res = await jupyter_routes.update_jupyter_workspace_config(
        auth = self.auth,
        workspace_id = self.id,
        config_body = self.to_json(),
        debug_api = debug_api,
        debug_num_stacks_to_drop = debug_num_stacks_to_drop,
        parent_class = self.__class__.__name__,
        session = session
    )

    return res

# %% ../../nbs/classes/50_DomoJupyter.ipynb 14
@dataclass
class DomoJupyter_Content:
    name: str
    folder: str
    last_modified: dt.datetime
    file_type: str
    content: str

    auth: dmda.DomoJupyterAuth = field(repr=False)

    default_export_folder: str = "export"

    def __post_init__(self):
        dmda.test_is_jupyter_auth(self.auth)

        if self.folder.endswith(self.name):
            self.folder = self.folder.replace(self.name, "")

    @classmethod
    def _from_json(cls, obj: dict, auth: dmda.DomoJupyterAuth):
        dd = util_dd.DictDot(obj) if not isinstance(obj, util_dd.DictDot) else obj

        dc = cls(
            name=dd.name,
            folder=dd.path,
            last_modified=parse(dd.last_modified),
            file_type=dd.type,
            auth=auth,
            content=obj.get("content"),
        )

        return dc

    def export_content(
        self,
        output_folder: str = None,
        file_name: str = None,
    ):
        output_folder = output_folder or os.path.join(
            self.default_export_folder, self.folder
        )

        file_name = file_name or self.name

        if not os.path.exists(output_folder):
            print(output_folder)
            os.makedirs(output_folder)

        content_str = self.content
        if isinstance(self.content, dict):
            content_str = json.dumps(self.content)

        output_path = os.path.join(output_folder, file_name)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(content_str)
            f.close()

        return output_path

    async def update(
        self,
        jupyter_folder: str = None,
        jupyter_file_name: str = None,
        debug_api: bool = False,
    ):
        if jupyter_folder and jupyter_file_name:
            content_patuh = f"{jupyter_folder}/{jupyter_file_name}"

        if len(self.folder) > 0:
            content_path = f"{self.folder}/{self.name}"

        else:
            content_path = self.name

            if content_path.lower().startswith(self.default_export_folder.lower()):
                content_path = content_path.replace(self.default_export_folder, "")

        content_path = "/".join(os.path.normpath(content_path).split(os.sep))

        return await jupyter_routes.update_jupyter_file(
            auth=self.auth,
            content_path=content_path,
            new_content=self.content,
            debug_api=debug_api,
            debug_num_stacks_to_drop=2,
            parent_class=self.__class__.__name__,
        )

# %% ../../nbs/classes/50_DomoJupyter.ipynb 15
@dataclass
class DomoJupyter:
    auth: dmda.DomoJupyterAuth = field(repr=False)
    content: [DomoJupyter_Content] = field(default=None)

    jupyter_token = None
    service_location = None
    service_prefix = None

    def __post_init__(self):
        dmda.test_is_jupyter_auth(self.auth)

        if hasattr(self.auth, "domo_password") and not isinstance(
            self.auth, dmda.DomoJupyterFullAuth
        ):
            self.auth = DomoJupyterFullAuth.convert_auth(
                full_auth=self.auth,
                jupyter_token=self.jupyter_token,
                service_location=self.service_location,
                service_prefix=self.service_prefix,
            )
        if hasattr(self.auth, "developer_token") and not isinstance(
            self.auth, DomoJupyterDeveloperToken
        ):
            self.auth = dmda.DomoJupyterTokenAuth.convert_auth(
                auth=self.auth,
                jupyter_token=self.jupyter_token,
                service_location=self.service_location,
                service_prefix=self.service_prefix,
            )

    async def get_content(
        self,
        debug_api: bool = False,
        return_raw: bool = False,
        is_recursive: bool = True,
        content_path: str = "",
    ):
        if is_recursive:
            res = await jupyter_routes.get_content_recursive(
                auth=self.auth,
                debug_api=False,
                content_path=content_path,
                debug_num_stacks_to_drop=3,
                parent_class=self.__class__.__name__,
            )
            content_ls = res.response

        else:
            res = await jupyter_routes.get_jupyter_content(
                auth=self.auth,
                debug_api=False,
                content_path=content_path,
                debug_num_stacks_to_drop=2,
                parent_class=self.__class__.__name__,
            )

            content_ls = res.response["content"]

        if return_raw:
            return res

        return [
            DomoJupyter_Content._from_json(obj, auth=self.auth) for obj in content_ls
        ]
