import json
import os
from datetime import datetime
from random import randint

from environment import Environment
from google.cloud import pubsub_v1


class CloudQueueService:
    """Service 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.
    """
    def __init__(self):
        """Initializes the CloudQueueService with appropriate environment variables and a PubSub client."""
        if not Environment.LIVE_SERVER:
            os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(os.path.dirname(__file__), '..', '..', Environment.gcloud_creds_filename)
        self.publisher = pubsub_v1.PublisherClient()

    def generate_task_id(self):
        """Generates a unique task id based on current time and a random number.

        Returns:
            str: The unique task id as a string.
        """
        return str(datetime.utcnow().timestamp() * 1000) + str(randint(0, 100000))

    def schedule_task(self, topic_id, task_description):
        """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
        """
        topic_path = self.publisher.topic_path(Environment.GCLOUD_PROJECT_ID, topic_id)

        # Construct the data (payload) of the message
        task = {"task_id": self.generate_task_id(), "task_description": task_description}
        data = json.dumps(task)
        data = data.encode("utf-8")

        # Add an attribute to the message
        attributes = {"task_type": "compute"}

        # Publish the message
        future = self.publisher.publish(topic_path, data, **attributes)
        print(f"Published message ID {future.result()}")

# CloudQueueService().schedule_task("storyit2", {"function": "follow_instagram_user", "username": "j.steinberg_"})
