a
    fD	                     @   sR   d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlmZ G dd dZ	dS )    N)datetime)randint)Environment)	pubsub_v1c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	CloudQueueServicezService to handle interaction with a Google Cloud PubSub queue.

    This service manages the publishing of tasks to a Google Cloud PubSub queue.

    Attributes:
        publisher: The PubSub client used to interact with Google Cloud PubSub.
    c                 C   s6   t js(tjtjtddt jtjd< t	
 | _dS )z]Initializes the CloudQueueService with appropriate environment variables and a PubSub client.z..GOOGLE_APPLICATION_CREDENTIALSN)r   LIVE_SERVERospathjoindirname__file__gcloud_creds_filenameenvironr   ZPublisherClient	publisherself r   O/var/www/html/python-backend/backend/services/scheduling/cloud_queue_service.py__init__   s    "zCloudQueueService.__init__c                 C   s"   t t  d t tdd S )zGenerates a unique task id based on current time and a random number.

        Returns:
            str: The unique task id as a string.
        i  r   i )strr   utcnow	timestampr   r   r   r   r   generate_task_id   s    z"CloudQueueService.generate_task_idc                 C   sf   | j tj|}|  |d}t|}|d}ddi}| j j||fi |}t	d|
   dS )a  Schedules a task by publishing it to a specified PubSub topic.

        The function creates a task with a unique id and the provided description, then publishes it
        to the provided topic id. It adds a task type attribute ("compute") to the message.

        Args:
            topic_id (str): The id of the PubSub topic to which the task should be published.
            task_description (dict): The description of the task to be scheduled.

        Returns:
            None
        )task_idtask_descriptionzutf-8Z	task_typeZcomputezPublished message ID N)r   
topic_pathr   GCLOUD_PROJECT_IDr   jsondumpsencodeZpublishprintresult)r   Ztopic_idr   r   taskdata
attributesfuturer   r   r   schedule_task    s    

zCloudQueueService.schedule_taskN)__name__
__module____qualname____doc__r   r   r'   r   r   r   r   r   
   s   r   )
r   r	   r   randomr   environmentr   Zgoogle.cloudr   r   r   r   r   r   <module>   s   