import json
import requests


def create_destination_connection_profile(project, location, destination_config, token):
    """
    This function will create the destination connection profile in Google Cloud DataStream
    :param project: Google Cloud project id mentioned in variables.py
    :param location: Google Cloud resource location, for example us-central1
    :param destination_config: destination config from variables.py
    :param token: Google Cloud auth token
    :return: True or False
    """

    d_profile_name = destination_config["destination_profile_name"]
    d_profile_id = destination_config["destination_profile_id"]
    bucket_name = destination_config["storage_bucket_name"]
    bucket_prefix = destination_config["storage_bucket_prefix"]

    url = f"https://datastream.clients6.google.com/v1alpha1/" \
          f"projects/{project}/locations/{location}" \
          f"/connectionProfiles?connectionProfileId={d_profile_id}"

    payload = json.dumps({
        "displayName": d_profile_name,
        "gcsProfile": {
            "bucketName": bucket_name,
            "rootPath": bucket_prefix
        }
    })
    headers = {
        'Authorization': token,
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    if response.status_code == 200:
        print(f"Destination connection profile {d_profile_id} created successfully")
        destination_connection_profile_stat = True
    elif response.status_code == 409:
        print(f"Destination connection profile {d_profile_id} already exist")
        destination_connection_profile_stat = True
    else:
        print(f"Issue while creating destination connection profile: {response.text}")
        destination_connection_profile_stat = False
    return destination_connection_profile_stat