# -*- coding:utf-8 -*-
"""
Function: set_custom_role.py moudle. This moudle mainly involves the
Setting Customized Role Permission function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2017-2020
"""
import sys
from scripts import common_function


def setcustomrole_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Setting Customized Role Permission
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setrole',
                                   help='''set custom role''')
    sub_parser.add_argument('-R', dest='role',
                            required=True,
                            choices=['CustomRole1', 'CustomRole2',
                                     'CustomRole3', 'CustomRole4'],
                            help='''custom role''')
    sub_parser.add_argument('-Pri',
                            dest='privilege',
                            required=True,
                            nargs='+',
                            choices=['Login', 'ConfigureComponents',
                                     'ConfigureSelf',
                                     'Kvm', 'Vmm', 'SecurityMgmt',
                                     'PowerControl', 'Diagnosis'],
                            help='custom role privilege. one or multiple '
                                 'values that are not duplicate can be set. '
                                 'use a space to separate multiple values')
    parser_dict['setrole'] = sub_parser

    return 'setrole'


def setcustomrole(client, args):
    """
    Function Description:Setting Customized Role Permission
    Parameter:client refishClient: class object
    args object:CLI command
    """
    # Process parameters.
    payload = init_payload(args)
    url = "/redfish/v1/AccountService/Roles/" + args.role

    resp = client.get_resource(url)
    if resp is None:
        return None

    if resp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
        if resp['status_code'] == common_function.REDFISH_STATUS_CODE_404:
            print('Failure: resource was not found')
        return resp

    resp = client.set_resource(url, payload)
    if resp is None:
        return None

    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_200:
        print_result(resp)

    else:
        if resp['status_code'] == common_function.REDFISH_STATUS_CODE_404:
            print("Failure: resource was not found")
        if resp['status_code'] == common_function.REDFISH_STATUS_CODE_400:
            message = resp['message']['error']['@Message.ExtendedInfo']
            print("Failure: %s" % common_function.change_message(
                message[0]['Message']))

    return resp


def print_result(resp):
    """
    Function Description:print result
    Parameter:resp dict: redfish interface result
    """
    # Some configuration fails.
    if resp['resource'].get('@Message.ExtendedInfo'):
        message = resp['resource']['@Message.ExtendedInfo']
        print("Failure: %s" % common_function.change_message(
            message[0]['Message']))
        sys.exit(common_function.UREST_STATUS_CODE_144)
    else:
        print('Success: successfully completed request')


def init_payload(args):
    """
    Function Description:init payload
    Parameter:args object:CLI command
    """
    payload = {}
    assignedprivileges = ['Login', 'ConfigureComponents', 'ConfigureSelf']
    assigneditem = []
    oemitem = []

    for privilege in args.privilege:
        if privilege in assignedprivileges:
            assigneditem += [privilege]
        else:
            oemitem.append("%s%s" % ('Oem', privilege))

    if assigneditem:
        payload['AssignedPrivileges'] = assigneditem

    payload['OemPrivileges'] = oemitem

    return payload


def check_parameter(parser, args):
    """
    Function Description:check CLI command
    Parameter:args object:CLI command
    parser ArgumentParser:subcommand ArgumentParser object
    """
    # If AssignedPrivileges is set, fill Login.
    # Login is a mandatory parameter.
    if 'ConfigureComponents' in args.privilege \
            or 'ConfigureSelf' in args.privilege:
        if 'Login' not in args.privilege:
            (args.privilege).append('Login')

    # Array duplication check
    if len(args.privilege) != len(list(set(args.privilege))):
        parser.error('the value of privilege is duplicate')
