# -*- coding: utf-8 -*-
"""
Function: set_sys_performance.py moudle. This moudle mainly involves the
 setting System Performance function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
import sys
from scripts import common_function


def setsysperformance_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    setting System Performance.
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    Modify: 2019.4.28 The help information is optimized.
    Return Value: subcommand
    """
    sub_parser = parser.add_parser('setsysperf',
                                   help='set system performance information')

    sub_parser.add_argument('-C', dest='cpu', type=int,
                            help='''CPU threshold percent''')

    sub_parser.add_argument('-M', dest='mem', type=int,
                            help='''memory threshold percent''')

    sub_parser.add_argument('-D', dest='hdd', type=int,
                            help='''hard disk threshold percent''')

    parser_dict['setsysperf'] = sub_parser

    return 'setsysperf'


def _printferrormessages(k, msgs):
    """
    #=========================================================================
    #   @Description:  printf error messages
    #   @Method:  _printferrormessages
    #   @Param:
    #   @Return:
    #   @Date:
    #=========================================================================
    """
    if msgs is None:
        return

    if k == 1:
        error = 'Failure: some of the settings failed. '
        error = error + 'possible causes include the following:'
        print(error)
        for msg_info in msgs:
            msg = msg_info['RelatedProperties'][0].replace(
                '#/Oem/%s/' % common_function.COMMON_KEY, '')
            print('         invalid property %s value' % msg)
    if k == 0:
        for i in range(k, len(msgs)):
            msg = msgs[i]['RelatedProperties'][0].replace(
                '#/Oem/%s/' % common_function.COMMON_KEY, '')
            if i == 0:
                print('Failure: invalid property %s value' % msg)
            else:
                print('         invalid property %s value' % msg)


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if args.cpu is None and args.mem is None and args.hdd is None:
        parser.error('at least one parameter must be specified')

    if args.cpu is not None:
        if args.cpu < 0 or args.cpu > 100:
            err = "argument -C: invalid choice: %s " \
                  "(choose from 0 to 100)" % args.cpu
            parser.error(err)

    if args.mem is not None:
        if args.mem < 0 or args.mem > 100:
            err = "argument -M: invalid choice: %s " \
                  "(choose from 0 to 100)" % args.mem
            parser.error(err)

    if args.hdd is not None:
        if args.hdd < 0 or args.hdd > 100:
            err = "argument -D: invalid choice: %s " \
                  "(choose from 0 to 100)" % args.hdd
            parser.error(err)


def setsysperformance(client, args):
    """
    #=========================================================================
    #   @Description:  set system performance information
    #   @Method:  setsysperformance
    #   @Param:
    #   @Return:
    #   @Date:
    #=========================================================================
    """

    slotid = client.get_slotid()

    if slotid is None:
        return None

    url = "/redfish/v1/systems/%s" % slotid
    resp = client.get_resource(url)

    if resp is None:
        return None
    if resp.get('status_code') != 200:
        return resp

    resp_inner_dic = common_function.get_vendor_value(resp)
    if 'CPUthresholdPercent' in resp_inner_dic:
        flag = "t"
    else:
        flag = "T"

    payload = get_payload(args, flag)

    resp = client.set_resource(url, payload)

    if resp.get('status_code') == 200:
        # Some of the settings failed
        if resp['resource'].get('@Message.ExtendedInfo') is not None:
            messages = resp['resource']['@Message.ExtendedInfo']
            _printferrormessages(1, messages)
            sys.exit(144)
        else:
            print('Success: successfully completed request')
    else:
        # Failure
        if resp.get('status_code') == 400:
            messages = resp['message']['error']['@Message.ExtendedInfo']
            _printferrormessages(0, messages)

    return resp


def get_payload(args, flag):
    """
    功能描述:初始化payload
    参数：args (list): parameter list
    flag (str): t or T
    parser (ArgumentParser):  subcommand parameter parser
    返回值：payload (dict)
    修改：None
    """
    payload = {"Oem": {common_function.COMMON_KEY: {}}}
    payload_vendor = payload['Oem'][common_function.COMMON_KEY]
    if args.cpu is not None:
        payload_vendor["CPU%shresholdPercent" % flag] = args.cpu
    if args.mem is not None:
        payload_vendor['Memory%shresholdPercent' % flag] = args.mem
    if args.hdd is not None:
        payload_vendor['HardDisk%shresholdPercent' % flag] = args.hdd
    return payload
