# -*- coding: utf-8 -*-
"""
Function: control_fru_power.py moudle. This moudle mainly involves the
 powering On or Off an FRU function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
from scripts import common_function


def controlfrupower_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    powering On or Off an FRU.
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    Modify: 2018-11-26 Add normal power-off parameters 'GracefulShutdown'
            2019.4.28 The help information is optimized.
    Return Value: subcommand
    """
    sub_parser = parser.add_parser('frupowerctrl',
                                   help='''FRU power control''')
    sub_parser.add_argument('-F', dest='Fru',
                            type=int, required=True,
                            help='''FRU id''')
    sub_parser.add_argument('-T', dest='ResetType',
                            choices=['On', 'ForceOff', 'ForceRestart',
                                     'Nmi', 'ForcePowerCycle',
                                     'GracefulShutdown'],
                            required=True,
                            help='''FRU power control options''')

    parser_dict['frupowerctrl'] = sub_parser

    return 'frupowerctrl'


def controlfrupower(client, args):
    """
    #====================================================================
    #   @Description:  control fru power entry
    #   @Method:  postfrupower
    #   @Param:
    #   @Return:
    #   @Date:
    #====================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/systems/%s/Actions/Oem/%s/ComputerSystem.FruControl" %\
          (slotid, common_function.COMMON_KEY)

    payload = {"FruID": args.Fru, "FruControlType": args.ResetType}

    resp = client.create_resource(url, payload)
    if resp is None:
        return None

    if resp.get('status_code') == 200:
        print('Success: successfully completed request')
    else:
        code_not_ok(resp)
    return resp


def code_not_ok(resp):
    """
    功能描述：redfish 接口返回来的code码非200
    参数：resp (dict): redfish 接口返回来的字典类型的数据
    返回值：None
    异常描述：None
    """
    if resp.get('status_code') == 400:
        messages = resp['message']['error']['@Message.ExtendedInfo'][0][
            'MessageId']
        error_message_dict = {
            'ActionFailedByPowerOff': 'Failure: action failed by powerOff',
            'CommandNot': 'Failure: command not supported',
            'ResourceInUse': 'Failure: resource in use',
            'FruNotExist': 'Failure: fru not exist'}
        for message_id in error_message_dict:
            if message_id in messages:
                print(error_message_dict.get(message_id))
                return

        msg = resp['message']['error']['@Message.ExtendedInfo'][0][
            'Message']
        print(msg)
    else:
        common_function.print_status_code(resp)
