# -*- coding:utf-8 -*-
"""
Function: get_sel.py moudle. This moudle mainly involves the
 querying Log Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
from scripts.common_function import INPUT_INFO


def getsel_init(parser, parser_list):
    """
    #==========================================================================
    #   @Method:  Register functions to
                  register methods used for obtaining SELs.
    #   @Param:   parser  major command argparser
                  parser_list  save subcommand parser list
    #   @Return:
    #   @author:
    #==========================================================================
    """
    sub_parser = parser.add_parser('getsel', help='''get SEL record''')
    sub_parser.add_argument('-PA', dest='PAGE',
                            choices=['Enabled', 'Disabled'],
                            required=False, help='get SEL record '
                                                 'information paging display')
    parser_list['getsel'] = sub_parser

    return 'getsel'


def print_sel_multiple_property(resp, sel_actual_count):
    """
    #==========================================================================
    #   @Method:  Display multiple SEL attribute values.
    #   @Param:   resp  Log object
                  sel_actual_count  Actual number of logs
    #   @Return:
    #   @author:
    #==========================================================================
    """

    # Display each SEL attribute.
    print("%-14s%-2s%-20s" % ('Id', ":", sel_actual_count))
    print("%-14s%-2s%-20s" % ('Severity', ":", resp['resource'].get('Severity', '')))
    print("%-14s%-2s%-20s" % ('EventTimestamp', ":",
                              resp['resource'].get('EventTimestamp', '')))
    print("%-14s%-2s%-20s" % ('EntryType', ":", resp['resource'].get('EntryType', '')))
    print("%-14s%-2s%-20s" % ('EventType', ":", resp['resource'].get('EventType', '')))
    print("%-14s%-2s%-20s" % ('Message', ":", resp['resource'].get('Message', '')))
    print("%-14s%-2s%-20s" % ('MessageId', ":", resp['resource'].get('MessageId', '')))
    print("%-14s%-2s%-20s" % ('EventId', ":", resp['resource'].get('EventId', '')))


def continue_or_break(user_input_count, count_tmp):
    """
    Function Description:Determine whether to continue or exit.
    Parameter:user_input_count int: number of user inputs
    count_tmp int:temporary count
    Modify: 2019.5.17 the pagination interaction method is optimized.
    Return Value: result of the redfish interface
    """
    if count_tmp == 0:
        strtemp = input(INPUT_INFO).strip()
        tmp = strtemp.replace('\r', '')
        if tmp == 'q':
            return None
        count_tmp = user_input_count
        print('-' * 50)
        return count_tmp

    return count_tmp


def print_sel_user_num(client, slotid, user_input_count, sel_actual_count):
    """
    #==========================================================================
    #   @Method:  Display some SELs.
    #   @Param:   client  RedfishClient object
                  slotid  Slot number
                  user_input_count    Number of user inputs
                  sel_actual_count    Actual number of SELs
    #   @Return:
    #   @author:
    #==========================================================================
    """
    print('-' * 50)
    count_tmp = user_input_count

    sel_uri = '/redfish/v1/Systems/%s/logservices/log1/entries/%s'
    while count_tmp > 0 and sel_actual_count > 0:
        url = sel_uri % (slotid, sel_actual_count)
        resp = client.get_resource(url)
        if resp is None:
            return None
        if resp['status_code'] == 200:
            # Invoke functions to display SEL attributes.
            print_sel_multiple_property(resp, sel_actual_count)
            sel_actual_count = sel_actual_count - 1
            count_tmp = count_tmp - 1
            print('-' * 50)
            tmp_value = continue_or_break(user_input_count, count_tmp)
            if tmp_value is None:
                return None
            count_tmp = tmp_value
        else:
            print('Failure: %d was not found' % sel_actual_count)
            sel_actual_count = sel_actual_count - 1
            count_tmp = count_tmp - 1

            print('-' * 50)
            tmp_value = continue_or_break(user_input_count, count_tmp)
            if tmp_value is None:
                return None
            count_tmp = tmp_value


def print_sel_all(client, slotid, sel_actual_count):
    """
    #==========================================================================
    #   @Method:  Display all SELs.
    #   @Param:   client  RedfishClient object
                  slotid  Slot number
                  sel_actual_count    Actual number of SELs
    #   @Return:
    #   @author:
    #==========================================================================
    """
    print('-' * 50)
    sel_uri = '/redfish/v1/Systems/%s/logservices/log1/entries/%s'
    while sel_actual_count:
        url = sel_uri % (slotid, sel_actual_count)
        resp = client.get_resource(url)
        if resp is None:
            return None
        # Obtain different log information.
        if resp['status_code'] == 200:
            print_sel_multiple_property(resp, sel_actual_count)

            sel_actual_count = sel_actual_count - 1
            print('-' * 50)
        else:
            print('Failure: %d was not found' % sel_actual_count)
            sel_actual_count = sel_actual_count - 1
            print('-' * 50)
            if sel_actual_count == 0:
                return None


def print_sel_user_input(client, slotid, user_input_count, sel_actual_count):
    """
    #==========================================================================
    #   @Method:  Obtain SEL functions when users enter parameters.
    #   @Param:   client   RedfishClient object
                  slotid   Slot number

                  sel_actual_count  Number of log events
    #   @Return:
    #   @author:
    #==========================================================================
    """
    if user_input_count < sel_actual_count:
        print_sel_user_num(client, slotid, user_input_count, sel_actual_count)
    else:
        print_sel_all(client, slotid, sel_actual_count)


def print_sel_default(client, sel_actual_count, slotid):
    """
    #==========================================================================
    #   @Method:  Obtain SEL functions when users do not enter parameters.
    #   @Param:   client  RedfishClient object
                  slotid  Slot number
                  resp    Log collection object
                  sel_actual_count  Actual number of logs
    #   @Return:
    #   @author:
    #==========================================================================
    """
    user_default_count = 10
    user_default_count_tmp = user_default_count
    sel_uri = '/redfish/v1/Systems/%s/logservices/log1/Entries/%s'
    print('-' * 50)
    while sel_actual_count:
        url = sel_uri % (slotid, sel_actual_count)
        resp = client.get_resource(url)
        if resp is None:
            return None
        if resp['status_code'] == 200:
            # Invoke functions to display SEL attributes.
            print_sel_multiple_property(resp, sel_actual_count)
            sel_actual_count = sel_actual_count - 1
            user_default_count_tmp = user_default_count_tmp - 1
            print('-' * 50)
            tmp_value = continue_or_break(user_default_count,
                                          user_default_count_tmp)
            if tmp_value is None:
                return None

            user_default_count_tmp = tmp_value
        else:
            print('Failure: %d was not found' % sel_actual_count)
            sel_actual_count = sel_actual_count - 1
            print('-' * 50)
            continue


def getsel(client, args):
    """
    Function Description:querying Log Information
    Parameter:client refishClient: class object
    args object:CLI command
    Modify: 2019.3.7 Add parse parameters.
    Return Value: resp dict:result of the redfish interface
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    url = "/redfish/v1/systems/%s/logservices/log1/entries" % slotid
    resp = client.get_resource(url)

    if resp is None:
        return None
    if resp['status_code'] == 404:
        print('Failure: resource was not found')
    elif resp['status_code'] == 200:
        # Obtain the number of log entries.
        sel_actual_count = resp['resource']['Members@odata.count']
        # Display information based on the parameters entered by users.
        if args.PAGE == "Disabled":
            user_input_count = sel_actual_count
            print_sel_user_input(client, slotid, user_input_count,
                                 sel_actual_count)
        else:
            print_sel_default(client, sel_actual_count, slotid)

    return resp
