# -*- coding:utf-8 -*-
"""
Function: delete_sp_file.py moudle. This moudle mainly involves the
Deleting a sp upgrade file function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2022-2022
"""

from scripts import version_comparator


INVALID_VALUE = None


def deletespfile_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Deleting a sp upgrade file
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('deletespfile',
                                   help='''delete sp file list''')
    sub_parser.add_argument('-F', dest='File', required=False,
                            help='''file to be deleted''')
    parser_dict['deletespfile'] = sub_parser
    return 'deletespfile'


def deletespfile(client, args):
    """
    Function Description:Deleting a sp upgrade file
    Parameter:client refishClient: class object
    args object:CLI command
    """
    slotid = client.get_slotid()
    if slotid is None:
        return INVALID_VALUE
    # 本次操作需要删除的文件列表
    file_list = args.File.split(";") if ";" in args.File else [args.File]
    if not check_params(client, file_list, slotid):
        return INVALID_VALUE
    url = "/redfish/v1/Managers/%s/SPService/SPFWUpdate/1/Actions/SPFWUpdate.DeleteSPUpdateFile" % slotid
    # Request body
    payload = {'FileList': file_list}
    resp = client.create_resource(url, payload)
    if resp is None:
        return INVALID_VALUE
    if resp['status_code'] == 200:
        print('The command succeed to run')
    elif resp['status_code'] == 404:
        print('The command failed to run because the 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")
        elif "SPFWUpdate.DeleteSPUpdateFile is not supported" in change_message(message[0]['Message']):
            print("The command failed to run because the iBMC version is earlier than 3.6.0.1.")
        else:
            print("Failure: " + change_message(message[0]['Message']))
    return resp


def check_params(client, file_list, slotid):
    # 系统上的SP文件列表
    sp_file_list = get_sp_file_list(client, slotid)
    for file in file_list:
        # 删除接口传参只允许传.zip
        if ".zip" != file[-4:]:
            print("The command failed to run because the current file %s is not a .zip file." % file)
            return False
        # 只可删除当前系统存在的SP文件
        if file not in sp_file_list:
            print("The %s file does not exist." % file)
            return False
    return True


def change_message(messageinfo):
    if (messageinfo[0] >= 'A' and messageinfo[0] <= 'Z') \
            and (messageinfo[-1] == '.'):
        return messageinfo[0].lower() + messageinfo[1:-1]
    return messageinfo


def get_sp_file_list(client, slotid):
    """
    获取SP升级文件列表
    """
    url = "/redfish/v1/Managers/%s/SPService" % slotid
    resp = client.get_resource(url)
    if resp is None or resp.get("status_code", None) is None:
        print('no data available for the resource')
        return INVALID_VALUE
    if resp['status_code'] == 200:
        info = resp.get('resource', None)
        file_list = info.get("FileList")
        if file_list is None or len(file_list) == 0:
            print('no data available for the resource')
            return INVALID_VALUE
        sp_file_list = []
        for file in file_list:
            sp_file_list.append(file["Name"])
        return sp_file_list
    elif resp['status_code'] == 404:
        print('Failure: resource was not found')
        return INVALID_VALUE
    elif resp['status_code'] == 500:
        print("Failure: the request failed due to an internal service error")
        return INVALID_VALUE

    return resp


def get_bmc_version(client):
    """
    获取当前BMC版本
    """
    url = "/redfish/v1/UpdateService/FirmwareInventory/ActiveBMC"
    resp = client.get_resource(url)
    if resp is None:
        return INVALID_VALUE
    if resp['status_code'] == 404:
        print('Failure: resource was not found')
        return INVALID_VALUE
    elif resp['status_code'] == 200:
        return resp.get('resource', None)["Version"]
    return resp
