# By: Riasat Ullah
# This file contains functions that sync up conditional routing information stored in db with that in cache.

from cache_queries import cache_routing
from dbqueries import db_routing
from taskcallrest import settings


def store_all_enabled_conditional_routing_in_cache(conn, client, timestamp):
    '''
    Stores all enabled conditional routes in cache for all organizations.
    :param conn: db connection
    :param client: cache client
    :param timestamp: timestamp this request is being made on
    '''
    if settings.CACHE_ON:
        all_routes = db_routing.get_all_enabled_org_conditional_routes(conn, timestamp)
        cache_routing.store_conditional_routes(client, all_routes)


def get_organization_enabled_conditional_routes(conn, client, timestamp, organization_id):
    '''
    Gets a list of all the enabled conditional routes that an organization has.
    :param conn: db connection
    :param client: cache client
    :param timestamp: timestamp this request is being made on
    :param organization_id: ID of the organization
    :return: (list) of ConditionalRoute objects
    '''
    if settings.CACHE_ON:
        routes = cache_routing.get_conditional_routes(client, organization_id)
    else:
        routes = db_routing.get_conditional_routing(conn, timestamp, org_id=organization_id, enabled_only=True,
                                                    id_on_ref=False)
    return routes


def update_organization_conditional_routes_in_cache(conn, client, timestamp, organization_id):
    '''
    Update the conditional routes of an organization stored in cache
    :param conn: db connection
    :param client: cache client
    :param timestamp: timestamp this request is being made on
    :param organization_id: ID of the organization
    '''
    if settings.CACHE_ON:
        org_routes = db_routing.get_conditional_routing(conn, timestamp, org_id=organization_id, enabled_only=True,
                                                        id_on_ref=False)
        cache_routing.store_org_conditional_routes(client, organization_id,  org_routes)
