# -*- coding:utf-8 -*-
"""
Function: del_sp_cfg.py moudle. This moudle mainly involves the deleting the
 Upgrade File or Configuration File of the Smart Provisioning Service function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""


def delspcfg_init(parser, parser_list):
    """
    Function Description:initializing the Command for deleting the
    upgrade file or configuration file 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.
            2020.1.10 delete SPNetDev.
            2020.1.10 delete disk erase configuration.
    Return Value: subcommand
    """
    sub_parser = parser.add_parser('delspcfg', help='''delete SP service''')
    sub_parser.add_argument('-T', dest='Type', required=True,
                            choices=['RAIDCfg', 'FWUpdateCfg', 'DriveEraseCfg'],
                            help='''SP service type''')

    parser_list['delspcfg'] = sub_parser

    return 'delspcfg'


def delspcfg(client, args):
    """
    #=====================================================================
    #   @Method: delete sp service SP configuration deletion function entry
    #   @Param:
    #   @Return:
    #   @author:
    #=====================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    # Request URL
    action = "/SPService/Actions/SPService.DeleteFile"
    url = "/redfish/v1/Managers/" + slotid + action
    # Request body
    payload = {'Type': args.Type}
    resp = client.create_resource(url, payload)
    if resp is None:
        return None

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

    elif resp['status_code'] == 404:
        print('Failure: resource was not found')

    # Error message response message
    elif resp['status_code'] == 400:
        message = resp['message']['error']['@Message.ExtendedInfo']
        messageid = message[0]['MessageId'].split('.')[-1]
        if messageid == "OperationNotSupported":
            print("Failure: this operation is not supported")
        else:
            print("Failure: " + change_message(message[0]['Message']))
    return resp


def change_message(messageinfo):
    """
    #==========================================================================
    #   @Method:  changemessage
    Change strings with capitalized first letters and
    ended with '.' into strings with lowercase first letters and delete '.'.
    #   @Param:
    #   @Return:
    #   @author:
    #==========================================================================
    """
    if (messageinfo[0] >= 'A' and messageinfo[0] <= 'Z') \
            and (messageinfo[-1] == '.'):
        return messageinfo[0].lower() + messageinfo[1:-1]

    return messageinfo
