import requests
import json


def post_to_layer_group_api(conn, url, the_json, quiet=True):
    """
    post content layergroup endpoint

    Parameters
    ----------
    conn : dict,
        Connection parameters
        Example: conn = {'domain': 'https://earthobs.defra.gov.uk',
                            'username': '<insert-username>',
                            'access_token': '<insert-access-token>'}

    url : str
        url of which layer group to access

    the_json : dict
        the dictionary that gets parsed to the 'json' parameter of the POST request

    Returns
    -------
    json response from layergroup api
    
    """    

    headers={'Content-type': 'application/json','User-Agent': 'eods scripting'}

    params = {'username':conn['username'],'api_key':conn['access_token']}

    # post the the EODS layer group api endpoint
    if quiet:
        try:
            response = requests.post(
                url,
                params=params,
                headers=headers,
                json=the_json,
                verify=False
                )
            # raise an error if the response status is not successful
            response.raise_for_status()

            # if response is successful, print the response text
            print(f'\n## Response posting to {response.url} was successful ...')
            print(f'\n## Response text : \n{response.text}')
            print(f'\n## Response content : \n{response.content}')
            
            return json.loads(response.content)
            
        except Exception as error:
            print('Error caught as exception')
            print(error)
    else:
        response = requests.post(
            url,
            params=params,
            headers=headers,
            json=the_json,
            verify=False
            )

        response.raise_for_status()

        # if response is successful, print the response text
        print(f'\n## Response posting to (CONTAINS SENSITIVE AUTHENTICATION DETAILS, DO NOT SHARE) {response.url} was successful ...')
        print(f'\n## Response text : \n{response.text}')
        print(f'\n## Response content : \n{response.content}')
        
        return json.loads(response.content)