# By: Riasat Ullah
# This file contains queries that store/fetch monitor checks data in cache. The concealed reference ID of the checks
# are used as the key in the cache. The storage and removal requests are sent with the unmasked check ref ID. They are
# converted to the concealed form in the cache functions here.

from objects.check import Check
from utils import cache_names, helpers, key_manager
import json
import uuid


def store_heartbeats(client, checks_list):
    '''
    Store the details of heartbeat checks in cache.
    :param client: cache client
    :param checks_list: (list) of Check objects
    '''
    data = dict()
    for chk in checks_list:
        key = key_manager.conceal_reference_key(chk.check_ref_id)
        data[key] = json.dumps(chk.to_dict(), default=helpers.jsonify_unserializable)
    client.hmset(cache_names.heartbeats, data)


def store_single_heartbeat(client, check_obj):
    '''
    Stores the details of a single heartbeat check.
    :param client: cache client
    :param check_obj: Check object
    '''
    key = key_manager.conceal_reference_key(check_obj.check_ref_id)
    client.hset(cache_names.heartbeats, key, json.dumps(check_obj.to_dict(), default=helpers.jsonify_unserializable))


def get_heartbeat(client, key):
    '''
    Get a heartbeat check object.
    :param client: cache client
    :param key: (concealed) check key
    :return: (dict) details of the api key
    '''
    json_check = client.hget(cache_names.heartbeats, key)
    if json_check is not None:
        return Check.create_check(json.loads(json_check))
    else:
        return None


def get_all_heartbeats(client):
    '''
    Gets all the heartbeats from cache.
    :param client: cache client
    :return: (dict) {check_id: Check, ...}
    '''
    check_json = client.hgetall(cache_names.heartbeats)
    data = dict()
    if check_json is not None:
        for ref_ in check_json:
            check_obj = Check.create_check(json.loads(check_json[ref_]))
            data[check_obj.check_id] = check_obj
    return data


def remove_single_heartbeat(client, check_ref_id):
    '''
    Remove a single heartbeat from cache.
    :param client: cache client
    :param check_ref_id: (unmasked) reference ID of the check
    '''
    if isinstance(check_ref_id, uuid.UUID):
        key = key_manager.conceal_reference_key(check_ref_id)
    else:
        key = check_ref_id
    client.hdel(cache_names.heartbeats, key)


def remove_all_heartbeats(client):
    '''
    Remove all heartbeat checks from cache.
    :param client: cache client
    '''
    client.delete(cache_names.heartbeats)
