from slurpit.apis.baseapi import BaseAPI
from slurpit.models.taskscheduler import TaskScheduler
from slurpit.utils.utils import handle_response_data, json_to_toon_bytes

class TaskSchedulerAPI(BaseAPI):
    def __init__(self, base_url, api_key, verify):
        """
        Initializes a new instance of the TaskSchedulerAPI class.

        Args:
            base_url (str): The root URL for the API endpoints.
            api_key (str): The API key used for authenticating requests.
            verify (bool): Verify HTTPS Certificates.
        """
        formatted_url = "{}/api".format(base_url if base_url[-1] != "/" else base_url[:-1])
        self.base_url = formatted_url
        super().__init__(api_key, verify)

    async def get_taskschedulers(self, offset: int = 0, limit: int = 1000, export_csv: bool = False, export_df: bool = False, format: str = "json"):
        """
        Retrieve a list of task scheduler records.

        Args:
            offset (int): The starting index of the records to fetch.
            limit (int): The maximum number of records to return in one call.
            export_csv (bool): If True, returns the data in CSV format as bytes (Deprecated).
            export_df (bool): If True, returns the data as a pandas DataFrame (Deprecated).
            format (str): The desired output format ("json", "csv", "dataframe", "toon"). Default is "json".

        Returns:
            list[TaskScheduler] | bytes | pd.DataFrame: A list of TaskScheduler objects or data in requested format.
        """
        url = f"{self.base_url}/taskscheduler"
        response = await self._pager(url, offset=offset, limit=limit)
        return handle_response_data(response, TaskScheduler, export_csv, export_df, format=format)

    async def get_taskscheduler(self, id: int, format: str = "json"):
        """
        Retrieve a single task scheduler record.

        Args:
            id (int): The ID of the task scheduler record to retrieve.
            format (str): The desired output format ("json", "toon"). Default is "json".

        Returns:
            TaskScheduler | bytes: The task scheduler record or TOON bytes.
        """
        url = f"{self.base_url}/taskscheduler/{id}"
        response = await self.get(url)
        if response:
            if format == "toon":
                return json_to_toon_bytes(response.json())
            return TaskScheduler(**response.json())

    async def create_taskscheduler(self, data: dict, format: str = "json"):
        """
        Create a new task scheduler record.

        Args:
            data (dict): The task scheduler data to create. \n
                         The dictionary should include the following keys: \n
                         - "name" (str): Name of the task scheduler record.
                         - "starts_at" (str): The date and time when the task starts. Example: "2023-04-03 12:41:24".
                         - "launch" (str): Frequency of the task. Allowed values: "once", "hourly", "daily", "weekly", "monthly", "yearly", "cron_style".
                         - "description" (str): Description of the task scheduler record.
                         - "action" (str): Action to perform. Allowed values: "start_scraper", "start_scanner", "start_profiler".
                         - "planning_id" (int, optional): The ID of the planning associated with the task.
                         - "repeat_every" (int, optional): Frequency interval for repeating the task.
                         - "repeat_at" (str, optional): Time of day to repeat the task.
                         - "repeat_on" (str, optional): Day(s) of the week or month to repeat the task.
                         - "repeat_days" (str, optional): Specific days to repeat the task.
                         - "cron_style" (str, optional): Cron-style expression for the task schedule.
                         - "disabled" (int, optional): Indicates if the task is disabled. Allowed values: 0, 1.
                         - "type" (str, optional): Type of the task. Example: "shell".
            format (str): The desired output format ("json", "toon"). Default is "json".

        Returns:
            TaskScheduler | bytes: The created task scheduler record or TOON bytes.
        """
        url = f"{self.base_url}/taskscheduler"
        response = await self.post(url, data)
        if response:
            if format == "toon":
                return json_to_toon_bytes(response.json())
            return TaskScheduler(**response.json())

    async def update_taskscheduler(self, id: int, data: dict, format: str = "json"):
        """
        Update an existing task scheduler record.

        Args:
            id (int): The ID of the task scheduler record to update.
            data (dict): The task scheduler data to update. \n
                         The dictionary can include the following keys: \n
                         - "name" (str): Name of the task scheduler record.
                         - "starts_at" (str): The date and time when the task starts.
                         - "launch" (str): Frequency of the task.
                         - "description" (str): Description of the task scheduler record.
                         - "action" (str): Action to perform.
                         - "planning_id" (int): The ID of the planning associated with the task.
                         - "repeat_every" (int): Frequency interval for repeating the task.
                         - "repeat_at" (str): Time of day to repeat the task.
                         - "repeat_on" (str): Day(s) of the week or month to repeat the task.
                         - "repeat_days" (str): Specific days to repeat the task.
                         - "cron_style" (str): Cron-style expression for the task schedule.
                         - "disabled" (int): Indicates if the task is disabled.
                         - "type" (str): Type of the task.
            format (str): The desired output format ("json", "toon"). Default is "json".

        Returns:
            TaskScheduler | bytes: The updated task scheduler record or TOON bytes.
        """
        url = f"{self.base_url}/taskscheduler/{id}"
        response = await self.put(url, data)
        if response:
            if format == "toon":
                return json_to_toon_bytes(response.json())
            return TaskScheduler(**response.json())

    async def delete_taskscheduler(self, id: int, format: str = "json"):
        """
        Delete a task scheduler record.

        Args:
            id (int): The ID of the task scheduler record to delete.
            format (str): The desired output format ("json", "toon"). Default is "json".

        Returns:
            dict | bytes: The result of the delete operation or TOON bytes.
        """
        url = f"{self.base_url}/taskscheduler/{id}"
        response = await self.delete(url)
        if response:
            if format == "toon":
                return json_to_toon_bytes(response.json())
            return response.json()
