# By: Riasat Ullah
# This file contains variables specifically for Datadog.

from constants import static_vars, var_names
from taskcallweb import settings
from urllib.parse import urlencode
from utils import s3
import base64
import hashlib


# datadog s3 credential file variables
datadog_s3_bucket = 'taskcall-prod-data'
datadog_s3_key = 'credentials/datadog_credentials.json'

# url paths
datadog_access_token_path = '{0}/oauth2/v1/token'

# datadog variable names
var_dd_oid = 'dd_oid'
var_dd_org_name = 'dd_org_name'

# string variable names
str_datadog_domain = 'datadog_domain'
str_datadog_site = 'datadog_site'


def get_datadog_credentials():
    '''
    Get the credentials needed for handling and making API calls to Datadog.
    :return: (dict) of credentials
    '''
    creds = s3.read_json(datadog_s3_bucket, datadog_s3_key)
    return creds


def get_datadog_to_tc_redirect_uri():
    '''
    Get the TaskCall redirect uri to send to Datadog.
    :return: (str) redirect uri
    '''
    ref_dict = static_vars.regional_urls
    if settings.TEST_SERVER:
        ref_dict = static_vars.regional_test_server_urls
    path = ref_dict[settings.REGION][var_names.redirect_base] +\
        '/configurations/services/integrations/datadog/authorize'
    return path


def get_datadog_oauth_path(site, serv_ref):
    '''
    Format the Datadog oauth path for a given account.
    :param site: datadog site to send the request to
    :param serv_ref: the service ref ID that will be used to generate the code challenge
    :return: (str) oauth path
    '''
    dd_creds = get_datadog_credentials()
    oauth_root = '{0}/oauth2/v1/authorize?'.format(site)
    params = {
        'redirect_uri': get_datadog_to_tc_redirect_uri(),
        'client_id': dd_creds[var_names.client_id],
        'response_type': 'code',
        'code_challenge': base64.urlsafe_b64encode(hashlib.sha256(serv_ref.encode()).digest()).decode().rstrip('='),
        'code_challenge_method': 'S256'
    }
    oauth_path = oauth_root + urlencode(params)
    return oauth_path


def get_web_path_us_tc_datadog_authorization(site, domain):
    '''
    Get the web url path in the US region to redirect a Datadog authorization request to
    from the EU region when the account is situated in the US.
    :param site: datadog site the request came from
    :param domain: datadog domain
    :return: (str) url path
    '''
    ref_dict = static_vars.regional_urls
    if settings.TEST_SERVER:
        ref_dict = static_vars.regional_test_server_urls
    path = ref_dict[static_vars.aws_us_ohio][var_names.redirect_base] +\
        '/configurations/services/integrations/datadog/initiate?site={0}&domain={1}'.format(site, domain)
    return path
