# By: Riasat Ullah
# This file contains queries that handle api keys storage in cache.

from utils import cache_names, helpers
import json


def store_api_keys(client, key_details):
    '''
    Store the details of all api keys in cache.
    :param client: cache client
    :param key_details: (dict) -> {api key: [list], ...}
    '''
    assert isinstance(key_details, dict) and len(key_details) > 0
    data = dict()
    for key in key_details:
        data[key] = json.dumps(key_details[key], default=helpers.jsonify_unserializable)
    client.hmset(cache_names.api_keys, data)


def store_single_api_key(client, key, details):
    '''
    Stores the details of a single api key.
    :param client: cache client
    :param key: api key
    :param details: (dict) details of the api key
    '''
    client.hset(cache_names.api_keys, key, json.dumps(details, default=helpers.jsonify_unserializable))


def get_api_key_details(client, key):
    '''
    Get the details of a particular api key.
    :param client: cache client
    :param key: api key
    :return: (dict) details of the api key
    '''
    json_details = client.hget(cache_names.api_keys, key)
    if json_details is not None:
        return json.loads(json_details)
    return None


def remove_single_api_key(client, key):
    '''
    Removes the details of a particular api key from cache.
    :param client: cache client
    :param key: api key
    '''
    client.hdel(cache_names.api_keys, key)


def remove_all_api_keys(client):
    '''
    Remove all api keys from cache.
    :param client: cache client
    '''
    client.delete(cache_names.api_keys)
