# -*- coding:utf-8 -*-
"""
Function: set_power_limit.py moudle. This moudle mainly involves the
Setting Power Capping function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
import sys
from scripts import common_function


def setpowerlimit_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Setting Power Capping
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setpowerlimit',
                                   help='''set power limit''')
    sub_parser.add_argument('-L', dest='limit',
                            required=False,
                            help='''power limit value\
                            (Disabled or integer value)''')
    sub_parser.add_argument('-E', dest='exception',
                            required=False,
                            choices=['NoAction', 'HardPowerOff'],
                            help='''power limit exception action''')
    parser_dict['setpowerlimit'] = sub_parser

    return 'setpowerlimit'


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if not (args.limit or args.exception):
        parser.error('at least one parameter of -L and -E must be specified')
    if args.limit is not None and args.limit != 'Disabled':
        try:
            int(args.limit)
        except ValueError:
            parser.error('-L must be Disabled or an integer')


def setpowerlimit(client, args):
    """
    Function Description:Setting Power Capping
    Parameter:client refishClient: class object
    args object:CLI command
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    url = "/redfish/v1/Chassis/%s/Power" % slotid

    resp = client.get_resource(url)
    if resp.get('status_code') != common_function.REDFISH_STATUS_CODE_200:
        common_function.get_error_info(resp)
        return resp

    payload = init_payload(args)

    resp = client.set_resource(url, payload)
    if resp is None:
        return None
    # Modify: 2019.12.10 Modify error resolution method.
    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        messages = resp['resource'].get('@Message.ExtendedInfo')
        if messages is None:
            print('Success: successfully completed request')
            return resp
        error_info = messages[0].get('Message')
        print("Failure: %s" % error_info)
        sys.exit(common_function.UREST_STATUS_CODE_144)
    elif resp['status_code'] == common_function.REDFISH_STATUS_CODE_400:
        common_function.get_error_info(resp)

    return resp


def init_payload(args):
    """
    Function Description:init payload
    Parameter:args object:CLI command
    """
    payload = {"PowerControl": [{"PowerLimit": {}}]}
    if args.limit is not None:
        if args.limit == 'Disabled':
            payload['PowerControl'][0]['PowerLimit']['LimitInWatts'] = None
        else:
            payload['PowerControl'][0]['PowerLimit']['LimitInWatts'] = int(
                args.limit)
    if args.exception is not None:
        payload['PowerControl'][0]['PowerLimit']['LimitException'] = \
            args.exception
    return payload
