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

# %% auto 0
__all__ = ['DomoTrigger_Schedule', 'DomoTrigger', 'DomoJob', 'DomoJob_RemoteDomoStats']

# %% ../../nbs/classes/50_DomoApplication_Job.ipynb 3
from dataclasses import dataclass, field
from typing import List, Optional

import httpx

from nbdev.showdoc import patch_to
import domolibrary.utils.DictDot as util_dd
import domolibrary.client.DomoAuth as dmda
import datetime  as dt

from pprint import pprint

import domolibrary.routes.application as application_routes

import domolibrary.utils.convert as cc

# %% ../../nbs/classes/50_DomoApplication_Job.ipynb 5
@dataclass
class DomoTrigger_Schedule:
    schedule_text: str = None
    schedule_type: str = "scheduleTriggered"

    minute: int = None
    hour: int = None
    minute_str: str = None
    hour_str: str = None

    @classmethod
    def _from_str(cls, s_text, s_type):
        sched = cls(schedule_type=s_type, schedule_text=s_text)

        try:
            parsed_hour = s_text.split(" ")[2]
            parsed_minute = s_text.split(" ")[1]

            if "*" in parsed_hour or "/" in parsed_hour:
                sched.hour_str = parsed_hour
            else:
                sched.hour = int(float(parsed_hour))
            if "*" in parsed_minute:
                sched.minute_str = parsed_minute
            else:
                sched.minute = int(float(parsed_minute))

            return sched

        except Exception as e:
            print(f"unable to parse schedule {s_text}")
            print(e)

    def to_obj(self):
        return {"hour": int(self.hour), "minute": int(self.minute)}

    def to_schedule_obj(self):
        minute = self.minute_str if self.minute_str is not None else str(self.minute)
        hour = self.hour_str if self.hour_str is not None else str(self.hour)
        return {
            "eventEntity": f"0 {minute} {hour} ? * *",
            # old value on Jan 13
            # "eventEntity": f'0 {minute} {hour} 1/1 * ? *',
            "eventType": self.schedule_type,
        }


@dataclass
class DomoTrigger:
    id: str
    job_id: str
    schedule: List[DomoTrigger_Schedule] = None



@dataclass
class DomoJob:
    auth : dmda.DomoAuth = field(repr = False)
    id: str
    name: str
    description: str
    user_id: str
    application_id: str
    customer_id: str
    execution_timeout: int
    
    execution_payload: dict
    share_state: dict
    created_dt: dt.datetime
    updated_dt :dt.datetime
    
    triggers : List[DomoTrigger] = field(default_factory=[])

    
    # entity_ids: list
    # remote_instance: str
    # job_type: str
    # entity_type: str
    # max_indexing_time_min: int
    # variance_percent: int
    # min_update_frequency_min: int
    # sql_query: str
    # notify_user_ids: list
    # metrics_dataset_id: str
    # notify_group_ids: list
    # notify_email_addressess: list
    # resources_requests: str
    # resources_limits: str

    triggers: List[DomoTrigger] = None

    def _generate_base_json(obj):
            return {
            "id":obj['jobId'],
            "application_id" : obj['applicationId'],
            "customer_id" : obj['customerId'],
            "name"  : obj['jobName'],
            "description" : obj['jobDescription'],
            "user_id" : obj['userId'],
            "execution_timeout" : obj['executionTimeout'],
            "execution_payload": obj['executionPayload'],
            "share_state" : obj['shareState'],
            'created_dt' : cc.convert_epoch_millisecond_to_datetime(obj['created']),
            'updated_dt' : cc.convert_epoch_millisecond_to_datetime(obj['updated'])
            
            
            # entity_ids=(
            #     dd.executionPayload.watcherParameters.entityIds
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # job_type=(
            #     dd.executionPayload.watcherParameters.type
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # entity_type=(
            #     dd.executionPayload.watcherParameters.entityType
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # max_indexing_time_min=(
            #     dd.executionPayload.watcherParameters.maxIndexingTimeInMinutes
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # variance_percent=(
            #     dd.executionPayload.watcherParameters.variancePercent
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # min_update_frequency_min=(
            #     dd.executionPayload.watcherParameters.minDataUpdateFrequencyInMinutes
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # sql_query=(
            #     dd.executionPayload.watcherParameters.sqlQuery
            #     if dd.executionPayload.watcherParameters
            #     else []
            # ),
            # "notify_user_ids" : obj['executionPayload']['notifyUserIds'],
            # "notify_group_ids" : obj['executionPayload']['notifyGroupIds'],
            # "notify_email_addressess":obj['executionPayload']['notifyEmailAddresses'],
            # "metrics_dataset_id":obj['executionPayload']['metricsDatasetId'],
            # "resources_requests": obj['resources']['requests']['memory'],
            # "resources_limits":  obj['resources']['limits']['memory']
    }


    @classmethod
    def _from_json(cls, obj, auth):
        triggers_ls = obj.get("triggers", None)

        triggers_dj = [
            DomoTrigger(
                id=tg.get("triggerId"),
                job_id=tg.get("jobId"),
                schedule=DomoTrigger_Schedule._from_str(
                    s_text=tg.get("eventEntity"), s_type=tg.get("eventType")
                ),
            )
            for tg in triggers_ls
        ] if triggers_ls else []

        base_obj = cls._generate_base_json(obj)

        return cls(
            auth = auth,
            ** base_obj,
            triggers = triggers_dj,
        )

    def to_json(self):
        body = {
            "jobName": self.name,
            "jobDescription": self.description,
            "executionTimeout": self.execution_timeout,
            "accounts": [],
            "executionPayload": {
                "notifyUserIds": self.notify_user_ids or [],
                "notifyGroupIds": self.notify_group_ids or [],
                "notifyEmailAddresses": self.notify_email_addressess or [],
                "watcherParameters": {
                    "entityIds": self.entity_ids,
                    "type": self.job_type,
                    "entityType": self.entity_type,
                    "maxIndexingTimeInMinutes": self.max_indexing_time_min,
                    "variancePercent": self.variance_percent,
                    "sqlQuery": self.sql_query,
                },
                "metricsDatasetId": self.metrics_dataset_id,
            },
            "resources": {
                "requests": {"memory": self.resources_requests},
                "limits": {"memory": self.resources_limits},
            },
            "triggers": (
                [self.triggers[0].schedule.to_schedule_obj()]
                if len(self.triggers) > 0
                else []
            ),
        }
        return body

# %% ../../nbs/classes/50_DomoApplication_Job.ipynb 8
@dataclass
class DomoJob_RemoteDomoStats(DomoJob):
    remote_instance : str = None

    @classmethod 
    def _from_json( cls, obj, auth):
        base_class = cls._generate_base_json(obj)

        return cls(
            base_class, 
            remote_instance = cls._get_remote_instance(obj.remoteInstance)
        )
                
    @staticmethod
    def _get_remote_instance(remote_instance):
        return remote_instance.replace(".domo.com", "")
    
    @classmethod
    async def get_by_id(
        cls,
        application_id,
        job_id,
        auth: dmda.DomoAuth,
        debug_api: bool = False,
        session: Optional[httpx.AsyncClient] = None,
        debug_num_stacks_to_drop=2,
        return_raw :bool = False
    ):
        res = await cls._get_by_id(
            application_id = application_id,
            job_id = job_id,
            auth = auth,
            debug_api = debug_api,
            session = session,
            debug_num_stacks_to_drop= debug_num_stacks_to_drop)

        if return_raw:
            return res
        
        cls._from_json(
            obj = res.response,
            auth = auth
        )
    

# %% ../../nbs/classes/50_DomoApplication_Job.ipynb 11
@patch_to(DomoJob)
async def execute(
    self,
    debug_api: bool = False,
    session: Optional[httpx.AsyncClient] = None,
):

    res = await application_routes.execute_job(
        auth=self.auth,
        application_id=self.application_id,
        job_id=self.job_id,
        debug_api=debug_api,
        session=session,
    )

    return res
