# -*- coding:utf-8 -*-
"""
Function: get_event_subscription.py moudle. This moudle mainly involves the
Querying an Event Subscription function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
from scripts.common_function import REDFISH_STATUS_CODE_200
from scripts.common_function import REDFISH_STATUS_CODE_404

PRINT_FORMAT = '%-17s%-2s%-20s'


def geteventsubscription_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying an Event Subscription
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('geteventsubs',
                                   help='''get event subscription''')
    parser_dict['geteventsubs'] = sub_parser

    return 'geteventsubs'


def get_single_event_message(client, str_event):
    """
    Function Description:  get single event message
    Parameter:client refishClient: class object
    str_event str:event url
    """
    resp_single = client.get_resource(str_event)
    if resp_single is None:
        return None
    if resp_single['status_code'] == REDFISH_STATUS_CODE_200:

        print(PRINT_FORMAT % ('Id', ':',
                              resp_single['resource'].get('Id', '')))
        print(PRINT_FORMAT % ('Name', ':',
                              resp_single['resource'].get('Name', '')))
        print(PRINT_FORMAT % ('Destination', ':',
                              resp_single['resource'].get('Destination', '')))
        print(PRINT_FORMAT % ('EventTypes', ':',
                              ','.join(resp_single['resource'].get('EventTypes', ''))))
        print(PRINT_FORMAT % ('HttpHeaders', ':',
                              resp_single['resource'].get('HttpHeaders', '')))
        print(PRINT_FORMAT % ('Protocol', ':',
                              resp_single['resource'].get('Protocol', '')))
        print(PRINT_FORMAT % ('Context', ':',
                              resp_single['resource'].get('Context', '')))

        print_messageid(resp_single)

        print_originresource(resp_single)
    else:
        print('Failure: %s was not found' % (str_event.split('/')[-1]))

    print('-' * 50)
    return resp_single


def print_originresource(resp_single):
    """
    Function Description: print result
    Parameter:resp_single dict:redfish value
    """
    len_resp = len(resp_single['resource'].get('OriginResources', []))
    if len_resp > 0:
        origin_arr = []
        for arr_id in range(0, len(
                resp_single['resource']['OriginResources'])):
            origin_arr.append(
                resp_single['resource']['OriginResources'][arr_id].get('@odata.id', ''))

        print(PRINT_FORMAT % ('OriginResources', ':',
                              ','.join(origin_arr)))
    else:
        print(PRINT_FORMAT % ('OriginResources', ':', None))


def print_messageid(resp_single):
    """
    Function Description: print result
    Parameter:resp_single dict:redfish value
    """
    len_info = len(resp_single['resource'].get('MessageIds', ''))
    if len_info > 0:
        print(PRINT_FORMAT % ('MessageIds', ':',
                              ','.join(
                                  resp_single['resource'].get('MessageIds', ''))))
    else:
        print(PRINT_FORMAT % ('MessageIds', ':', None))


def geteventsubscription(client, _):
    """
    Function Description: Deleting an Event Subscription
    Parameter:client refishClient: class object
    """
    # Obtain the subscription event collection.
    url = "/redfish/v1/EventService/Subscriptions"
    resp = client.get_resource(url)

    if resp is None:
        return None
    if resp['status_code'] == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
    elif resp['status_code'] == REDFISH_STATUS_CODE_200:
        resp_one = get_members_resp(client, resp)
        if resp_one is None:
            return None
    return resp


def get_members_resp(client, resp):
    """
    Function Description: information about the keyword Members
    Parameter:client refishClient: class object
    resp dict: Interface /redfish/v1/EventService/Subscription value
    Return Value: resp_one dict:last Member's redfish interface value
    """
    resp_one = None
    event_count = len(resp['resource'].get('MessageIds', ''))
    if event_count <= 0:
        print('No event subscription')
        return resp
    tmp_count = 0
    print('-' * 50)
    while tmp_count < event_count:
        for key in resp.get('resource', {}).get('Members', {})[tmp_count]:
            str_event = resp.get('resource', {}).get('Members', {})[tmp_count].get(key, {})
            resp_one = get_single_event_message(client, str_event)
            if resp_one is None:
                return None
        tmp_count += 1
    return resp
