# -*- coding:utf-8 -*-
"""
Function: get_ps_redundancy.py moudle. This moudle mainly involves the
Querying the PSU Redundancy Mode function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
import sys
from scripts.common_function import REDFISH_STATUS_CODE_200
from scripts.common_function import REDFISH_STATUS_CODE_404
from scripts.common_function import UREST_STATUS_CODE_148
from scripts import common_function


def getpsredundancy_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying the PSU Redundancy Mode
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getpowerredun',
                                   help='''get power redundancy''')
    parser_dict['getpowerredun'] = sub_parser

    return 'getpowerredun'


def print_func(ps_list_name, ps_list):
    """
    Function Description: Display lists in specified formats.
    Parameter:ps_list_name str: array name
    ps_list list: array list
    """
    index = 0
    length = len(ps_list)
    for_str = '|'
    while index < length:
        if index == 0:
            outstring = '%-20s: %-8s' % (ps_list_name, ps_list[index])
        else:
            outstring = '%s%-2s%-8s' % (outstring, for_str, ps_list[index])
        index += 1
    print(outstring)


def get_active_name(powersupplies, active_mode, active_name):
    """
    Function Description: Obtain the actual PSU name.
    Parameter:powersupplies list: redfish interface value
    active_mode str: active mode (Sharing or Failover)
    active_name list: active names
    """
    length = len(powersupplies)
    str_format = '{0:20}: {1}'
    if active_mode == '0':
        print(str_format.format('Mode', 'Sharing'))
        index = 0
        while index < length:
            state = powersupplies[index]["Status"]['State']
            if state == 'Enabled':
                active_name.append(powersupplies[index]['Name'])
            index += 1
    else:
        print(str_format.format('Mode', 'Failover'))
        index = 0
        while index < length:
            oem_dict = powersupplies[index][common_function.OEM_KEY]
            verdor_dict = oem_dict[common_function.COMMON_KEY]
            state = verdor_dict['ActiveStandby']
            if state == 'Active':
                active_name.append(powersupplies[index]['Name'])
            index += 1


def get_exp_mode(resp, powersupplies):
    """
    Function Description:Obtain the expected PSU working mode and working PSU.
    Parameter:resp dict: redfish interface value
    powersupplies list: redfish PowerSupplies value
    """
    str_format = '{0:20}: {1}'
    pctrl = resp['resource'].get('PowerControl', {})[0]
    expred = pctrl['Oem'][common_function.COMMON_KEY].get('ExpectedRedundancy', {})
    re_odata_id = expred['@odata.id']
    redundancy = resp['resource'].get('Redundancy', {})
    mode = redundancy[int(re_odata_id.split(r'/')[7])].get('Mode', '')
    psu_array = pctrl['Oem'][common_function.COMMON_KEY].get('ExpectedActivePSU', {})
    # Obtain the expected active PSU.
    index = 0
    name_list = []
    health_lsit = []
    state_lsit = []
    while index < len(psu_array):
        psu_odata_id = psu_array[index]['@odata.id']
        power_list = powersupplies[int(psu_odata_id.split(r'/')[7])]
        name_list.append(power_list.get('Name', ''))
        health_lsit.append(power_list.get('Status', {}).get('Health', ''))
        state_lsit.append(power_list.get('Status', {}).get('State', ''))
        index += 1
    print('[PredictedPSUStatus]')
    print(str_format.format("Mode", mode))
    print_func('ActivePSU', name_list)
    print_func('Health', health_lsit)
    print_func('State', state_lsit)


def print_info():
    """
    Function Description:Display information.
    """
    str_format = '{0:20}: {1}'
    print('[ActualPSUStatus]')
    print(str_format.format('Mode', None))
    print(str_format.format("ActivePSU", None))
    print('-' * 30)
    print('[PredictedPSUStatus]')
    print(str_format.format('Mode', None))
    print(str_format.format("ActivePSU", None))
    print(str_format.format("Health", None))
    print(str_format.format("State", None))


def getpsredundancy(client, _):
    """
    Function Description:Display lists in specified formats.
    Parameter:client refishClient: class object
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/Chassis/" + slotid + "/Power"
    resp = client.get_resource(url)
    if resp is None:
        return None

    if resp['status_code'] == REDFISH_STATUS_CODE_200:
        # Obtain the actual PSU working mode and working PSU.
        len_power = len(resp['resource']['PowerSupplies'])
        if len_power == 0:
            print_info()
            return resp
        print_psu(resp)
    elif resp['status_code'] == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')

    return resp


def print_psu(resp):
    """
    Function Description: print result
    Parameter:resp (dict): redfish interface value
    """
    powersupplies = resp['resource']['PowerSupplies']
    if resp['resource']['PowerControl'][0].get('Oem') is None:
        print('Failure: resource was not found')
        sys.exit(UREST_STATUS_CODE_148)
    redundancy = powersupplies[0]['Redundancy'][0]['@odata.id']
    active_mode = redundancy.split(r'/')[7]
    print('[ActualPSUStatus]')
    active_name = []
    get_active_name(powersupplies, active_mode, active_name)
    outstring = '%-20s: ' % "ActivePSU"
    index = 0
    while index < len(active_name):
        if index == 0:
            outstring = "%s%s" % (outstring, active_name[index])
        else:
            outstring = "%s %s" % (outstring, active_name[index])
        index += 1
    print(outstring)
    print('-' * 30)
    # Obtain the expected PSU working mode.
    get_exp_mode(resp, powersupplies)
