# By: Riasat Ullah
# This file contains functions that sync up email assignee data in the db with that in cache.

from cache_queries import cache_email_assignees
from dbqueries import db_organizations
from taskcallrest import settings
from utils import helpers


def store_all_email_assignees_in_cache(conn, client, timestamp):
    '''
    Store the details of all email assignees in cache.
    :param conn: db connection
    :param client: cache client
    :param timestamp: timestamp this request is being made on
    '''
    if settings.CACHE_ON:
        all_email_assignees = db_organizations.get_email_assignees(conn, timestamp)
        cache_email_assignees.store_email_assignees(client, all_email_assignees)


def get_email_assignee_details(conn, client, timestamp, emails, store_misses=True):
    '''
    Gets the details of email assignee(s).
    :param conn: db connection
    :param client: cache client
    :param timestamp: timestamp this request is being made on
    :param emails: (str or list of str) email address(es)
    :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: (dict) -> {email: [org ID, pol ID, serv ID]}
    '''
    emails = helpers.get_string_list(emails, check_for_email=True)
    retrieved_details = dict()
    cache_miss_emails = []

    if settings.CACHE_ON:
        retrieved_details = cache_email_assignees.get_email_assignees(client, emails)
        if len(retrieved_details) != len(emails):
            cache_miss_emails = list(set(emails).difference(set(retrieved_details.keys())))
    else:
        cache_miss_emails = emails

    if len(cache_miss_emails) > 0:
        details_from_db = db_organizations.get_email_assignees(conn, timestamp, cache_miss_emails)
        retrieved_details = {**retrieved_details, **details_from_db}

        if store_misses and settings.CACHE_ON:
            cache_email_assignees.store_email_assignees(client, retrieved_details)

    return retrieved_details
