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

PF = '{0}{1}'


def setstoragecontroller_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
     setting Controller Attributes.
    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('setraid',
                                   help='''set RAID controller''')
    sub_parser.add_argument('-I', dest='controllerid',
                            type=int, required=True,
                            help='''RAID controlelr ID''')
    sub_parser.add_argument('-CS', dest='copybackstate',
                            type=str, required=False,
                            choices=['True', 'False'],
                            help='whether copyback is enabled for specified '
                                 'RAID controller')
    sub_parser.add_argument('-SCBS', dest='smartercopybackstate',
                            type=str, required=False,
                            choices=['True', 'False'],
                            help='''whether SMART error copyback is enabled for
    the specified raid controller''')
    sub_parser.add_argument('-JS', dest='jbodstate',
                            type=str, required=False,
                            choices=['True', 'False'],
                            help='''whether JBOD is enabled''')
    parser_dict['setraid'] = sub_parser

    return 'setraid'


def check_resp(messages):
    """
    #=====================================================================
    #   @Method:  Process some success messages.
    #   @Param:   messages, error message
    #   @Return:
    #   @author:
    #=====================================================================
    """
    print("Failure: some of the settings failed. possible causes include the "
          "following: ")
    length = len(messages)
    index = 0
    while index < length:
        message_id = "iBMC.1.0.CurrentStatusNotSupportOperation"
        if message_id == messages[index]['MessageId']:
            m_str = messages[index]['RelatedProperties'][0]
            rep = "#/StorageControllers/0/Oem/%s/" % common_function.COMMON_KEY
            m_str = m_str.replace(rep, "")
            m_str = "%s %s" % ("modification of the property", m_str)
            check_info = messages[index]['Message'].replace("it", m_str)
        else:
            check_info = messages[index]['Message'].replace(
                "Oem/%s/" % common_function.COMMON_KEY, "")
        message = "%s%s" % \
                  (check_info[0].lower(), check_info[1:len(check_info) - 1])
        print(PF.format('         ', message))
        index += 1


def string_to_bool(string):
    """
    #=========================================================================
    #   @Description:  string_to_bool
    #
    #   @author:
    #   @Date: 2017 08 24
    #=========================================================================
    """
    # Modify: 2019.12.31 string to bool
    if string == 'False':
        return False
    return True


def full_payload(args, payload):
    """
    #=====================================================================
    #   @Method:  Fill the body
    #   @Param:   args Input parameter list
    #             payload  body
    #   @Return:  True or False
    #   @author:
    #=====================================================================
    """
    oem_dict = payload['StorageControllers'][0]['Oem']
    payload_inner_dic = oem_dict[common_function.COMMON_KEY]
    if args.copybackstate:
        payload_inner_dic['CopyBackState'] = string_to_bool(args.copybackstate)

    if args.smartercopybackstate:
        value = args.smartercopybackstate
        payload_inner_dic['SmarterCopyBackState'] = string_to_bool(value)

    if args.jbodstate:
        payload_inner_dic['JBODState'] = string_to_bool(args.jbodstate)


def check_error_info(messages):
    """
    #=====================================================================
    #   @Method:  Process setting failure messages.
    #   @Param:   messages, error message
    #   @Return:
    #   @author:
    #=====================================================================
    """
    index = 0
    while index < len(messages):
        message_id = "iBMC.1.0.CurrentStatusNotSupportOperation"
        if message_id == messages[index]['MessageId']:
            m_str = messages[index]['RelatedProperties'][0]
            rep = "#/StorageControllers/0/Oem/%s/" % common_function.COMMON_KEY
            m_str = m_str.replace(rep, "")
            m_str = "%s %s" % ("modification of the property", m_str)
            check_info = messages[index]['Message'].replace("it", m_str)
        else:
            message = messages[index]['Message']
            rep = "StorageControllers/0/Oem/%s/" % common_function.COMMON_KEY
            check_info = message.replace(rep, "")
        message = "%s%s" % \
                  (check_info[0].lower(), check_info[1:len(check_info) - 1])
        if index == 0:
            print(PF.format('Failure: ', message))
        else:
            print(PF.format('         ', message))
        index += 1


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser object:subcommand ArgumentParser object
    """
    if not (args.copybackstate or args.smartercopybackstate or args.jbodstate):
        parser.error('at least one parameter must be specified')


def setstoragecontroller(client, args):
    """
    #==========================================================================
    #   @Method:  Set controller attributes
    #   @Param:   client:; args: CLI parameter
    #   @Return:  dict: Successful, 'status_code', Response status code 200;
        'resource', URL node information
    #   @author:
    #==========================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    # Determine whether a storage system exists.
    systems = "/redfish/v1/Systems/" + slotid
    storage = "/Storages/RAIDStorage" + str(args.controllerid)
    resp = client.check_storages(systems, storage, '-I')
    if resp is None:
        return None
    if resp['status_code'] != 200:
        return resp

    payload = {
        "StorageControllers": [
            {
                common_function.OEM_KEY: {
                    common_function.COMMON_KEY: {}
                }
            }
        ]
    }
    full_payload(args, payload)
    url = systems + storage
    resp = client.set_resource(url, payload)
    if resp is None:
        return None

    if resp['status_code'] == 200:
        if resp['resource'].get('@Message.ExtendedInfo') is not None:
            messages = resp['resource']['@Message.ExtendedInfo']
            check_resp(messages)
            sys.exit(144)
        else:
            print('Success: successfully completed request')

    elif resp['status_code'] == 400:
        messageinfo = resp['message']['error']['@Message.ExtendedInfo']
        check_error_info(messageinfo)
    return resp
