# By: Riasat Ullah
# This file contains queries that handle conditional routing information in cache.

from objects.conditional_route import ConditionalRoute
from utils import cache_names, helpers
import json


def store_conditional_routes(client, routes: dict):
    '''
    Stores conditional routes in the cache.
    :param client: cache client
    :param routes: (dict) -> {org ID : [ConditionalRoute, ...], }
    '''
    assert isinstance(routes, dict) and len(routes) > 0
    data = dict()
    for org_id in routes:
        org_routes = routes[org_id]
        routes_dict = []
        for item in org_routes:
            routes_dict.append(item.to_dict())
        data[org_id] = json.dumps(routes_dict, default=helpers.jsonify_unserializable)
    client.hmset(cache_names.organization_conditional_routes, data)


def store_org_conditional_routes(client, organization_id: int, routes: list):
    '''
    Store the conditional routes of a given organization.
    :param client: cache client
    :param organization_id: (int) ID of the organization
    :param routes: (list) of ConditionalRoute objects
    '''
    routes_dict = []
    for obj in routes:
        routes_dict.append(obj.to_dict())
    client.hset(cache_names.organization_conditional_routes, organization_id,
                json.dumps(routes_dict, default=helpers.jsonify_unserializable))


def get_conditional_routes(client, organization_id: int):
    '''
    Get all the conditional routes that an organization has.
    :param client: cache client
    :param organization_id: ID of the organization whose routes should be fetched
    :return: (list) of ConditionalRoute objects
    '''
    routes_json = client.hget(cache_names.organization_conditional_routes, organization_id)
    routes = []
    if routes_json is not None:
        routes_json_list = json.loads(routes_json)
        for item in routes_json_list:
            routes.append(ConditionalRoute.create_conditional_route(item))
    return routes


def remove_org_conditional_routes(client, organization_id: int):
    '''
    Deletes the conditional routes of a given organization
    :param client: cache client
    :param organization_id: ID of the organization to be deleted
    '''
    client.hdel(cache_names.organization_conditional_routes, organization_id)


def delete_conditional_routes_cache(client):
    '''
    Deletes the conditional routes cache itself.
    :param client: cache client
    '''
    client.delete(cache_names.organization_conditional_routes)
