import datetime
import json
import os
import uuid

from environment import Environment
from google.cloud import tasks_v2
from google.oauth2 import service_account
from google.protobuf import timestamp_pb2


class SchedulingService:

    @staticmethod
    def create_task(http_target, headers, from_now_in_seconds, http_method='GET', body=None):
        # Load credentials from the service account file
        try:
            credentials = Environment.GCP_CREDENTIALS

            client = tasks_v2.CloudTasksClient(credentials=credentials)

            queue_id = 'scheduled-verifications'

            # Construct the fully qualified queue name.
            parent = client.queue_path(Environment.GCLOUD_PROJECT_ID, 'us-central1', queue_id)

            # Calculate the timestamp when the task should be run based on 'in_seconds' parameter
            timestamp = timestamp_pb2.Timestamp()
            timestamp.FromDatetime(datetime.datetime.utcnow() + datetime.timedelta(seconds=from_now_in_seconds))

            task_id = uuid.uuid4()

            # Construct the request body.
            task = {
                'name': client.task_path(Environment.GCLOUD_PROJECT_ID, 'us-central1', queue_id, task_id),
                'schedule_time': timestamp,
                'http_request': {  # Specify the type of request.
                    'http_method': tasks_v2.HttpMethod[http_method],
                    'url': http_target,
                    'headers': headers
                }
            }

            if http_method == 'POST' and body:
                # Serialize the body to JSON and then encode it
                serialized_body = json.dumps(body)
                task['http_request']['body'] = serialized_body.encode()

            # Use the client to build and send the task.
            response = client.create_task(request={'parent': parent, 'task': task})

            print('Created task {}'.format(response.name))
            return True

        except Exception as e:
            print(f"Error in creating task: {e}")
            return False

# load_dotenv() # FOR TESTING ONLY
# SchedulingService.create_task("https://storyitapp.uc.r.appspot.com/verify/verify-content//18428658/sjmeyer02/?is_private=false&username=kimkardashian&bot_username=null&phone_number=+1123456789&offer_id=123&client_id=123", {"Authorization": os.environ.get("FLASK_API_KEY")}, 20) # FOR TESTING ONLY