# -*- coding:utf-8 -*-
"""
Function: add_sp_diagnose.py moudle. This moudle mainly involves the creating
 a Diagnosis Configuration Resource of the Smart Provisioning Service function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2019-2021
"""
import sys

from scripts import common_function


def addspdiagnose_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
     creating a diagnosis configuration resource of the Smart
      provisioning service
    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('addspdiagnose',
                                   help='create a diagnostic configuration '
                                        'for the Smart Provisioning service.')
    sub_parser.add_argument('-D', dest='DeviceType',
                            type=str, required=False,
                            choices=['CPU', 'Memory', 'Disk'],
                            help='''device type''')
    sub_parser.add_argument('-M', dest='Mode',
                            type=str, required=False,
                            choices=['Quick', 'Full'],
                            help='''diagnostic mode''')
    sub_parser.add_argument('-T', dest='DurationMinutes',
                            type=int, required=False,
                            help='diagnosis duration. '
                                 'This parameter needs to be added only when '
                                 'the CPU is diagnosed. The unit is minute. '
                                 'The default value is 5 minutes. '
                                 'The value ranges from 1 to 10000.')
    sub_parser.add_argument('-F', dest='file',
                            required=False,
                            help='local path is used to '
                                 'create a diagnostic configuration.')
    parser_dict['addspdiagnose'] = sub_parser

    return 'addspdiagnose'


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if (args.DeviceType or args.Mode or args.DurationMinutes is not None) \
            and args.file:
        parser.error('Parameter error. Set -D and -M and -T or set -F only.')
    if args.DurationMinutes is not None:
        if args.DurationMinutes > 10000 or args.DurationMinutes < 1:
            parser.error('Argument -T: Invalid choice: '
                         '%d (choose from 1 to 10000)'
                         % args.DurationMinutes)


def addspdiagnose(client, args):
    """
    Function Description:Creating a diagnosis configuration resource of
    the Smart Provisioning service.
    Parameter:client refishClient: class object
    args object:CLI command
    Modify: 2019.1.21 the prompt information when the Diagnosis
     duration is out of bounds.
    Return Value: resp dict:redfish interface value
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/Managers/" + slotid + "/SPService/SPDiagnose"
    resp = client.get_resource(url)
    if resp is None:
        return None
    if resp['status_code'] != 200:
        common_function.get_error_info(resp)
        return resp

    payload = get_payload(args)

    if args.file:
        try:
            payload = common_function.payload_file(args.file,
                                                   file_des='configuration')
        except common_function.CustomError as e:
            print(e)
            sys.exit(common_function.UREST_STATUS_CODE_2)

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

    if resp['status_code'] == 201:
        print('Success: successfully completed request.')

    else:
        common_function.get_error_info(resp)
    return resp


def get_payload(args):
    """
    功能描述：初始化payload
    参数：args (list):parameter list
    返回值：None
    异常描述：None
    """
    payload = {"Diagnose": []}
    payload_dic = {}
    if args.DeviceType:
        payload_dic["DeviceType"] = args.DeviceType
    if args.Mode:
        payload_dic["Mode"] = args.Mode
    if args.DurationMinutes is not None:
        payload_dic["DurationMinutes"] = args.DurationMinutes
    payload["Diagnose"].append(payload_dic)
    return payload
