import uuid
import json
import requests


def set_azure_cloudcheckr_application_service_assignment(AzureApiBearerToken, AzureReaderRoleId, AzureCloudCheckrApplicationServicePrincipalId, AzureSubscriptionId):
    """
    Sets the previously created CloudCheckr application to have a reader role assignment.

    https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-rest
    """

    RoleAssignmentId = str(uuid.uuid1())

    api_url = "https://management.azure.com/subscriptions/" +  AzureSubscriptionId + "/providers/Microsoft.Authorization/roleAssignments/" + RoleAssignmentId + "?api-version=2015-07-01"
    authorization_value = "Bearer " + AzureApiBearerToken
    role_assignment_data = json.dumps({"properties": {"principalId": AzureCloudCheckrApplicationServicePrincipalId, "roleDefinitionId": AzureReaderRoleId}})

    response = requests.put(api_url, headers={"Authorization": authorization_value, "Content-Type": "application/json"}, data=role_assignment_data)
    print(response.json())

    if "properties" in response.json():
        properties = response.json()["properties"]
        if "roleDefinitionId" in properties:
            return properties["roleDefinitionId"]
    print("Failed to set role assignment for the CloudCheckr Application to the specified subscription")
    return None