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

from cache_queries import cache_workflows
from dbqueries import db_workflows
from taskcallrest import settings


def get_organization_enabled_workflows(conn, client, timestamp, organization_id, store_misses=True):
    '''
    Gets a list of all the enabled workflows 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
    :param store_misses: (boolean) True if cache misses that had to be retrieved
            from the db must be stored in cache afterwards; False otherwise
    :return: (list) of workflow details
    '''
    workflows = None
    if settings.CACHE_ON:
        workflows = cache_workflows.get_workflows(client, organization_id)

    # If the workflow is still None, it means that the organization's workflows are not stored in the cache.
    # If it is a list, then it means that the organization is in the cache, but there just are not any workflows.
    if workflows is None:
        # This will return a list.
        workflows = db_workflows.get_workflows(conn, timestamp, organization_id,
                                               with_ref_id_maps=False, is_enabled=True)
        if settings.CACHE_ON and store_misses:
            cache_workflows.store_org_workflows(client, organization_id, workflows)

    return workflows


def update_organization_workflows_in_cache(conn, client, timestamp, organization_id):
    '''
    Update the workflows 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:
        workflows = db_workflows.get_workflows(conn, timestamp, organization_id,
                                               with_ref_id_maps=False, is_enabled=True)
        cache_workflows.store_org_workflows(client, organization_id, workflows)
