# -*- coding:utf-8 -*-
"""
Function: set_netmode.py moudle. This moudle mainly involves the
Setting iBMC Network Port Mode function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
import sys
from scripts.common_function import REDFISH_STATUS_CODE_404
from scripts.common_function import REDFISH_STATUS_CODE_200
from scripts.common_function import REDFISH_STATUS_CODE_400
from scripts.common_function import UREST_STATUS_CODE_144
from scripts import common_function

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


def setnetmode_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Setting iBMC Network Port Mode
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setnetmode',
                                   help='''set network port mode''')
    sub_parser.add_argument('-M', dest='NetworkPortMode',
                            type=str, required=True,
                            choices=['Fixed', 'Automatic'],
                            help='''network port mode''')
    parser_dict['setnetmode'] = sub_parser

    return 'setnetmode'


def package_request(args, payload):
    """
    Function Description:Encapsulate the request body.
    Parameter:args object:CLI command
    payload dict:redfish interface Parameter
    """
    oem = {}
    payload_inner_dic = {"NetworkPortMode": args.NetworkPortMode}
    oem[common_function.COMMON_KEY] = payload_inner_dic
    payload["Oem"] = oem


def part_err(err_message_mode):
    """
    Function Description:200 messages
    Parameter:ada_message dict:redfish interface value
    """
    idx = 0
    while idx < len(err_message_mode):
        check_info = err_message_mode[idx]['Message']
        message = "%s%s" % \
                  (check_info[0].lower(), check_info[1:len(check_info) - 1])
        message = message.replace("Oem/%s/" % common_function.COMMON_KEY, "")
        print('         %s' % message)
        idx += 1


def all_err(err_message_mode):
    """
    Function Description:400 messages
    Parameter:ada_message dict:redfish interface value
    """
    idx = 0
    while idx < len(err_message_mode):
        check_info = err_message_mode[idx]['Message']
        message = "%s%s" % \
                  (check_info[0].lower(), check_info[1:len(check_info) - 1])
        message = message.replace("Oem/%s/" % common_function.COMMON_KEY, "")
        if idx == 0:
            print('%s' % message)
        else:
            print('         %s' % message)
        idx += 1


def check_err_info(resp_netmode, code_netmode):
    """
    Function Description:Determine whether all attributes are set successfully.
    Parameter:resp_netmode dict:redfish interface value
    code_netmode int:redfish interface code
    """
    mess_netmode = resp_netmode.get("@Message.ExtendedInfo", "")
    len_mess = len(mess_netmode)
    if len_mess != 0:
        err_message_mode = resp_netmode["@Message.ExtendedInfo"]
    else:
        print('Success: successfully completed request')
        return None
    # Determine whether a problem permission exists.
    if (err_message_mode[0]['MessageId'] ==
            "iBMC.1.0.PropertyModificationNeedPrivilege"
            or err_message_mode[0]['MessageId'] ==
            "Base.1.0.InsufficientPrivilege"):
        print('Failure: you do not have the required permissions to perform '
              'this operation')
        return None
    # Network error message
    if code_netmode == REDFISH_STATUS_CODE_400:
        sys.stdout.write('Failure: ')
        all_err(err_message_mode)
        return None
    # 200 messages
    if code_netmode == REDFISH_STATUS_CODE_200:
        print(FAILURE_MESS)
        part_err(err_message_mode)
        sys.exit(UREST_STATUS_CODE_144)

    return resp_netmode


def set_mode_info(members_uri, client, args):
    """
    Function Description:Set the network port mode.
    Parameter:members_uri str:members uri
    client refishClient: class object
    args object:CLI command
    """
    # Encapsulate the request body.
    payload = {}
    package_request(args, payload)
    resp_netmode = client.get_resource(members_uri)
    if resp_netmode is None:
        return None
    if resp_netmode['status_code'] != REDFISH_STATUS_CODE_200:
        if resp_netmode['status_code'] == REDFISH_STATUS_CODE_404:
            print('Failure: resource was not found')
        return resp_netmode

    resp_netmode = client.set_resource(members_uri, payload)
    if resp_netmode is None:
        return None
    if resp_netmode['status_code'] == REDFISH_STATUS_CODE_200:
        check_err_info(resp_netmode['resource'], resp_netmode['status_code'])
    if resp_netmode['status_code'] == REDFISH_STATUS_CODE_400:
        check_err_info(resp_netmode['message']['error'],
                       resp_netmode['status_code'])

    return resp_netmode


def get_port_collection(client, slotid, args):
    """
    Function Description:Query collection information.
    Parameter:client refishClient:class object
    slotid str:manager id
    args object:CLI command
    """
    url = "/redfish/v1/managers/%s/EthernetInterfaces" % slotid
    resp_netmode = client.get_resource(url)
    if resp_netmode is None:
        return None
    if resp_netmode['status_code'] != REDFISH_STATUS_CODE_200:
        if resp_netmode['status_code'] == REDFISH_STATUS_CODE_404:
            print('Failure: resource was not found')
        return resp_netmode

    members_count = resp_netmode['resource']["Members@odata.count"]
    if members_count == 0:
        print("no data available for the resource")
        return resp_netmode
    # Set the network port mode.
    members_uri = resp_netmode['resource']['Members'][0]["@odata.id"]
    resp_netmode = set_mode_info(members_uri, client, args)

    return resp_netmode


def setnetmode(client, args):
    """
    Function Description:Setting iBMC Network Port Mode
    Parameter:client refishClient:class object
    args object:CLI command
    Return Value:ret dict:redfish value
    """
    slotid = client.get_slotid()
    if slotid is None:
        return None
    # Query collection information.
    ret = get_port_collection(client, slotid, args)
    return ret
