import logging
from typing import List, Optional

from isahitlab.api.task.api import TaskApi
from isahitlab.domain.task import TaskId
from isahitlab.operations.base import BaseAction
from tqdm import tqdm
from typeguard import typechecked
from isahitlab.helpers.list import divide_chunks

logger = logging.getLogger('isahitlab.replay_webhooks')


class ReplayWebhooksOperation(BaseAction):
    """Replay webhooks
    """

    _task_api : TaskApi

    @typechecked
    def run(
        self,
        task_id_in: List[TaskId],
        disable_progress_bar: Optional[bool] = False,
    ) -> int:
        """ Replay webhooks
        
        Args:
            task_id_in: List of the IDs of the tasks to redo
            disable_progress_bar: Disable the progress bar display


        """
        self._task_api = TaskApi(self._http_client)


        chunks = divide_chunks(task_id_in, 100)
                
        with tqdm(total=len(task_id_in),  disable=disable_progress_bar, desc="Register webhooks for replaying... ") as loader:
            for chunk in chunks:
                self._task_api.replay_webhooks( task_ids=chunk )
                loader.update(len(chunk))
        
        return len(task_id_in)
    