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

from taskcallrest 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 delete_external_account_map_from_file(integ_type, cache_key):
    '''
    Delete an account map for an integration for routing from 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 in account_maps:
            if cache_key in account_maps[integ_type]:
                account_maps[integ_type].remove(cache_key)

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