# -*- coding:utf-8 -*-
"""
Function: set_vmm.py moudle. This moudle mainly involves the
 setting the Virtual Media Encryption Enabling Status function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2020-2021
"""
from sys import stdout

import sys
from scripts import common_function

FAILURE_MESS = 'Failure: some of the settings failed.\
 possible causes include the following: '


def setvmm_init(parser, parser_list):
    """
    #=====================================================================
    #   @Method:Register command functions
    #   @Param:
    #   @Return:
    #   @author:
    #=====================================================================
    """
    sub_parser = parser.add_parser('setvmm',
                                   help='''set virtual media information''')
    sub_parser.add_argument('-S', dest='EncryptionEnabled',
                            type=str, required=True, choices=['False', 'True'],
                            help='''VMM encryption''')
    parser_list['setvmm'] = sub_parser

    return 'setvmm'


def setvmm(client, args):
    """
    #=====================================================================
    #   @Method:Command processing function
    #   @Param:
    #   @Return:
    #   @author:
    #   date:2017.08.29 11:10
    #=====================================================================
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None

    url, resp = common_function.get_cd_info(client, slotid)
    if url == "":
        return resp

    resp_vmm = client.get_resource(url)
    if resp_vmm is None:
        return None
    if resp_vmm['status_code'] == 200:
        # Set attributes
        resp_vmm = set_encryption(url, client, args)
    if resp_vmm['status_code'] == 404:
        print('Failure: resource was not found')

    return resp_vmm


def set_encryption(url, client, args):
    """
    #=====================================================================
    #   @Method:Set resource information
    #   @Param:
    #   @Return:
    #   @author:
    #=====================================================================
    """
    # Encapsulate the request body
    ret = package_request(args)
    if ret is None:
        return None
    # Set resource attributes
    resp_vmm = client.set_resource(url, ret)
    if resp_vmm is None:
        return None
    if resp_vmm['status_code'] == 200:
        flag = check_err_info(resp_vmm['resource'], resp_vmm['status_code'])
        if not flag:
            sys.exit(144)
    if resp_vmm['status_code'] == 400:
        check_err_info(resp_vmm['message']['error'], resp_vmm['status_code'])

    return resp_vmm


def check_err_info(resp_vmm, code_vmm):
    """
    #==========================================================================
    # @Method: Determine whether all attributes are set successfully.
    Query @Message.ExtendedInfo
    # @Param:resp_vmm
    # @Return:
    # @date:2017.08.30 13:09
    #==========================================================================
    """
    flag = False
    vmm_msge = resp_vmm.get("@Message.ExtendedInfo", "")
    # Determine whether the configuration is successful
    if vmm_msge == "":
        print('Success: successfully completed request')
        flag = True
    else:
        # Determine whether a permission problem occurs.
        #  The entire resource has only one type of permission
        mess_id = vmm_msge[0].get("MessageId", "")
        if mess_id in ["iBMC.1.0.PropertyModificationNeedPrivilege",
                       "Base.1.0.InsufficientPrivilege"]:
            print('Failure: you do not have the required permissions '
                  'to perform this operation')
        else:
            # Display of 400 messages
            resq_mess(vmm_msge, code_vmm)

    return flag


def resq_mess(vmm_msge, code_vmm):
    """
    #==========================================================================
    # @Method: Respond to messages
    # @Param:idx, err_message， code_vmm
    # @Return:
    # @author:
    #==========================================================================
    """
    if code_vmm == 200:
        print(FAILURE_MESS)
    else:
        stdout.write('Failure: ')
    idx = 0
    while idx < len(vmm_msge):
        mess_id = vmm_msge[idx].get("MessageId", "")
        if mess_id == "iBMC.1.0.EnableVMMEncryptionFailed":
            message = vmm_msge[idx].get('Resolution', "")
        else:
            message = vmm_msge[idx].get('Message', "")
        # Display messages
        message = "%s%s" % (message[0].lower(), message[1:len(message) - 1])
        message = message.replace("Oem/%s/" % common_function.COMMON_KEY, "")

        if code_vmm == 400 and idx == 0:
            print('%s' % message)
        else:
            print('         %s' % message)
        idx += 1


def package_request(args):
    """
    #=====================================================================
    #   @Method:Encapsulate the request body
    #   @Param:
    #   @date:2017.08.27 11:43
    #   @author:
    #=====================================================================
    """
    payload = {}
    oem = {}
    encryption_enabled = args.EncryptionEnabled == str(True)
    payload_inner_dic = {"EncryptionEnabled": encryption_enabled}
    oem[common_function.COMMON_KEY] = payload_inner_dic
    payload["Oem"] = oem
    return payload
