# -*- coding: utf-8 -*-
"""
Function: set_stateless.py moudle. This moudle mainly involves the
 setting Stateless Computing Information function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
import sys

from scripts import common_function


def setstateless_init(parser, parser_dict):
    """
    Function Description:set stateless information subcommand init
    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('setstatless',
                                   help='set stateless computation '
                                        'information')
    sub_parser.add_argument('-I', dest='managerid', type=str,
                            required=False,
                            help='''system manger ID''')
    sub_parser.add_argument('-M', dest='managerip', type=str,
                            required=False,
                            help='''system manger IP''')
    sub_parser.add_argument('-p', dest='managerport',
                            type=int, required=False,
                            help='''system manger port''')
    sub_parser.add_argument('-SC', dest='cenabled',
                            type=str, choices=['True', 'False'],
                            required=False,
                            help='''control power on enabled''')
    sub_parser.add_argument('-SA', dest='aenabled',
                            type=str, choices=['True', 'False'],
                            required=False,
                            help='''auto search enabled''')

    parser_dict['setstatless'] = sub_parser

    return 'setstatless'


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 msgs_info in msgs:
            replaces = '#/Oem/%s/Stateless/' % common_function.COMMON_KEY
            msg = msgs_info['RelatedProperties'][0].replace(replaces, '')
            print('         invalid property %s value' % msg)
    if k == 0:
        for i in range(k, len(msgs)):
            replaces = '#/Oem/%s/Stateless/' % common_function.COMMON_KEY
            msg = msgs[i]['RelatedProperties'][0].replace(replaces, '')
            if i == 0:
                print('Failure: invalid property %s value' % msg)
            else:
                print('         invalid property %s value' % msg)


def _stringtobool(strs):
    """
    #=========================================================================
    #   @Description:  string to boolean
    #   @Method:  _stringtobool
    #   @Param:
    #   @Return:
    #   @Date:
    #=========================================================================
    """
    if strs == 'False':
        return False
    return True


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if args.managerid is None \
            and args.managerip is None \
            and args.managerport is None \
            and args.cenabled is None \
            and args.aenabled is None:
        parser.error('at least one parameter must be specified')

    if args.managerport is not None:
        if args.managerport < 1 or args.managerport > 65535:
            err = "argument -p: invalid choice: '%s' (choose from 1 to 65535)" \
                  % args.managerport
            parser.error(err)


def setstateless(client, args):
    """
    #=========================================================================
    #   @Description:  set stateless information
    #   @Method:  setstateless
    #   @Param:
    #   @Return:
    #   @Date:
    #=========================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url = "/redfish/v1/managers/%s" % slotid
    resp = client.get_resource(url)
    if resp is None:
        return None
    if resp['status_code'] != 200:
        return resp

    payload = get_payload(args)

    resp = client.set_resource(url, payload)
    if resp.get('status_code') == 200:
        print_sucess_info(resp)
    else:
        if resp.get('status_code') == 400:
            messages = resp['message']['error']['@Message.ExtendedInfo']
            _printferrormessages(0, messages)

    return resp


def print_sucess_info(resp):
    """
     功能描述:打印信息
     参数：resp (dict): 通过/redfish/v1/managers/1 获取到的信息
     返回值：None
     修改：None
     """
    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')


def get_payload(args):
    """
    功能描述:初始化payload
    参数：args (list): parameter list
    parser (ArgumentParser): subcommand argument parser
    返回值：payload (dict)
    修改：None
    """
    payload = {"Oem": {common_function.COMMON_KEY: {"Stateless": {}}}}
    stateless = payload['Oem'][common_function.COMMON_KEY]['Stateless']
    if args.managerid is not None:
        stateless['SysManagerId'] = args.managerid
    if args.managerip is not None:
        stateless['SysManagerIP'] = args.managerip
    # Modify: 2019.11.25 Modify the error message.
    if args.managerport is not None:
        stateless['SysManagerPort'] = args.managerport
    if args.cenabled is not None:
        stateless['ControlPowerOnEnabled'] = _stringtobool(args.cenabled)
    if args.aenabled is not None:
        stateless['AutoSearchEnabled'] = _stringtobool(args.aenabled)
    return payload
