# By: Riasat Ullah
# This file contains functions that enable CDN management.

from taskcallweb import settings
from utils import file_storage, s3
import configuration


def create_cdn_cache_key(integ_type, account_id, group_id=None):
    '''
    Create a cache key for external account maps to be used for CDN management.
    :param integ_type: type of the integration
    :param account_id: ID of the external account (tenant ID, team ID, etc)
    :param group_id: secondary account ID (channel ID, etc)
    :return: (str) the cache key
    '''
    cache_key = None
    if integ_type in configuration.ALLOWED_CDN_HANDLED_INTEGRATIONS:
        cache_key = account_id
        if group_id is not None:
            cache_key += '+' + group_id
    return cache_key


def update_external_account_maps_file(integ_type, cache_key):
    '''
    Update the external account maps file that is used to direct integrations to their correct region with Lambda@Edge.
    :param integ_type: the type of integration
    :param cache_key: the cache key
    '''
    if integ_type in configuration.ALLOWED_CDN_HANDLED_INTEGRATIONS:
        bucket = file_storage.S3_BUCKET_TASKCALL_CLIENT_DATA[settings.REGION]
        key_path = file_storage.S3_KEY_EXTERNAL_ACCOUNT_MAPS

        # get the file from s3
        account_maps = s3.read_json(bucket, key_path)
        if integ_type not in account_maps:
            account_maps[integ_type] = []
        account_maps[integ_type].append(cache_key)

        # upload the file back into s3
        s3.update_json(bucket, key_path, account_maps)
