# By: Riasat Ullah
# This file contains queries that handle incident workflows in cache.

from utils import cache_names, helpers
import json


def store_workflows(client, workflows: dict):
    '''
    Stores workflows in the cache (associated to the organization they belong to).
    :param client: cache client
    :param workflows: (dict) -> {org ID : [ { workflow details ...}, ...], }
    '''
    assert isinstance(workflows, dict) and len(workflows) > 0
    data = dict()
    for org_id in workflows:
        data[org_id] = json.dumps(workflows[org_id], default=helpers.jsonify_unserializable)
    client.hmset(cache_names.organization_workflows, data)


def store_org_workflows(client, organization_id: int, workflows: list):
    '''
    Store the workflows of a given organization.
    :param client: cache client
    :param organization_id: (int) ID of the organization
    :param workflows: (list of dict) of workflow details
    '''
    client.hset(cache_names.organization_workflows, organization_id,
                json.dumps(workflows, default=helpers.jsonify_unserializable))


def get_workflows(client, organization_id: int):
    '''
    Get all the workflows of an organization.
    :param client: cache client
    :param organization_id: ID of the organization whose workflows should be fetched
    :return: (list of dict) of workflow details  |  None if organization is not in cache
    '''
    workflows_json = client.hget(cache_names.organization_workflows, organization_id)
    if workflows_json is not None:
        return json.loads(workflows_json)
    return None


def get_organization_ids_from_cached_workflows(client):
    '''
    Get the list of organization IDs whose workflows are stored in cache.
    :param client: cache client
    :return: (list) of organization IDs
    '''
    org_ids = client.hkeys(cache_names.organization_workflows)
    return [int(x) for x in org_ids] if org_ids is not None else []


def remove_organization_workflows(client, org_ids: list):
    '''
    Deletes the workflows of a given organization
    :param client: cache client
    :param org_ids: (list) of organization IDs
    '''
    if len(org_ids) > 0:
        client.hdel(cache_names.organization_workflows, *org_ids)


def remove_all_workflows(client):
    '''
    Deletes the workflows cache itself.
    :param client: cache client
    '''
    client.delete(cache_names.organization_workflows)
