# By: Riasat Ullah
# This file contains cache queries for status pages.

from utils import cache_names, helpers, var_names
import json


def store_single_status_page(client, page_details):
    '''
    Stores the live details of a status page along with its reference map ({concealed page ref: page url, ...})
    :param client: cache client
    :param page_details: (dict) current details and state of the status page
    '''
    assert isinstance(page_details, dict)
    page_url = page_details[var_names.url]
    page_ref_id = page_details[var_names.page_ref_id]

    client.hset(cache_names.status_pages, page_url, json.dumps(page_details, default=helpers.jsonify_unserializable))
    client.hset(cache_names.status_pages_ref_map, page_ref_id, page_url)


def get_single_status_page(client, page_url=None, page_ref_id=None):
    '''
    Fetch the details of a status page from cache.
    :param client: cache client
    :param page_url: URL of the status page
    :param page_ref_id: reference ID of the status page
    :return: (dict) current details and state of the status page
    '''
    if page_url is None and page_ref_id is not None:
        page_url = client.hget(cache_names.status_pages_ref_map, page_ref_id)
    json_details = client.hget(cache_names.status_pages, page_url)
    if json_details is not None:
        return helpers.un_jsonify_status_page_details(json_details)
    else:
        return None


def remove_single_status_page(client, page_ref_id):
    '''
    Remove the details of a status page and its reference map from cache.
    :param client: cache client
    :param page_ref_id: reference ID of the page that should be removed
    '''
    page_url = client.hget(cache_names.status_pages_ref_map, page_ref_id)
    if page_url is not None:
        client.hdel(cache_names.status_pages, page_url)
        client.hdel(cache_names.status_pages_ref_map, page_ref_id)


def store_pending_status_page_update(client, post_id):
    '''
    Store the details of an instance update or business impact that should be dispatched
    through the business impact monitor.
    :param client: cache client
    :param post_id: ID of the post
    '''
    client.rpush(cache_names.pending_status_page_updates, post_id)


def get_all_pending_status_page_updates(client):
    '''
    Gets all the pending instance updates (for subscribers).
    :param client: cache client
    :return: (list) [dict, ...]
    '''
    upd_list = client.lrange(cache_names.pending_status_page_updates, 0, -1)
    if upd_list is None:
        return []
    else:
        return upd_list


def remove_pending_status_page_updates(client, start, end):
    '''
    Remove all pending status page updates from cache.
    :param client: cache client
    :param start: starting index
    :param end: ending index
    '''
    client.ltrim(cache_names.pending_status_page_updates, start, end)
