# By: Riasat Ullah
# This file contains all variables and integrations for the Webex integration.

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


# webex s3 credential file variables
webex_s3_bucket = 'taskcall-prod-data'
webex_s3_key = 'credentials/webex_credentials.json'

# webex url paths
webex_organizations_path = 'https://webexapis.com/v1/organizations'
webex_token_retrieval_path = 'https://webexapis.com/v1/access_token'


def get_webex_credentials():
    '''
    Get the credentials needed for handling and making API calls to Webex.
    :return: (dict) of credentials
    '''
    creds = s3.read_json(webex_s3_bucket, webex_s3_key)
    return creds


def get_webex_to_tc_redirect_uri():
    '''
    Get the TaskCall redirect uri to send to Webex.
    :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/conference-bridges/integrations/webex/authorize'
    return path


def get_webex_oauth_path(state):
    '''
    Format the Webex oauth path for a given account.
    :param state: unique code to send in the url for verification
    :return: (str) oauth path
    '''
    webex_creds = get_webex_credentials()
    oauth_root = 'https://webexapis.com/v1/authorize?'
    params = {
        'redirect_uri': get_webex_to_tc_redirect_uri(),
        'client_id': webex_creds[var_names.client_id],
        'response_type': 'code',
        'state': state,
        'scope': 'spark:kms spark:organizations_read meeting:admin_schedule_read meeting:admin_schedule_write ' +
                 'meeting:admin_participants_read meeting:participants_write meeting:participants_read ' +
                 'meeting:schedules_read meeting:schedules_write'
    }
    oauth_path = oauth_root + urlencode(params)
    return oauth_path
