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


def setuserrole_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Setting a User Role
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setuserrole',
                                   help='''assign a role for a user''')
    sub_parser.add_argument('-N',
                            dest='name',
                            required=False,
                            help='user name. specify the user to be modified. '
                                 'if no user is specified, the command modifies'
                                 ' information about the current login user')
    sub_parser.add_argument('-R', dest='newrole',
                            required=True,
                            choices=['Administrator', 'Operator', 'Commonuser',
                                     'NoAccess',
                                     'CustomRole1', 'CustomRole2',
                                     'CustomRole3', 'CustomRole4'],
                            help='''new role''')

    parser_dict['setuserrole'] = sub_parser

    return 'setuserrole'


def setuserrole(client, args):
    """
    Function Description:Setting a User Role
    Parameter:client refishClient: class object
    args object:CLI command
    Return Value: resp dict:result of the redfish interface
    """
    if args.name is None:
        username = args.username
    else:
        username = args.name

    if args.newrole == 'NoAccess':
        args.newrole = 'Noaccess'

    payload = {"RoleId": args.newrole}

    url = "/redfish/v1/AccountService/Accounts"

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

    if resp['status_code'] != common_function.REDFISH_STATUS_CODE_200:
        error_message(resp)
        return resp

    resp = setuserrole_info(client, resp, username, payload)
    return resp


def setuserrole_info(client, resp, username, payload):
    """
    Function Description:set user role
    Parameter:client refishClient: class object
    resp dict:redfish interface value
    username str:user name
    payload dict:redfish interface Parameter
    """
    # Modify: 2019.12.21 Set the specified user role information.
    for user_id in resp['resource'].get('Members'):
        if username == user_id.get('UserName'):
            url = user_id.get('@odata.id')
            user_resp = client.get_resource(url)
            if user_resp is None:
                return None
            if user_resp['status_code'] \
                    != common_function.REDFISH_STATUS_CODE_200:
                error_message(user_resp)
                return user_resp

            # set user role info
            set_resp = client.set_resource(url, payload)
            if set_resp is None:
                return None

            if set_resp['status_code'] \
                    == common_function.REDFISH_STATUS_CODE_200:
                print('Success: successfully completed request')
                return set_resp

            error_message(set_resp)
            return set_resp
    # user does not exist
    print('Failure: user does not exist')
    return resp


def error_message(resp):
    """
    Function Description:print error message
    Parameter:resp dict:redfish interface value
    """
    message = resp['message']['error']['@Message.ExtendedInfo']

    if resp['status_code'] == common_function.REDFISH_STATUS_CODE_404:
        print("Failure: resource was not found")
    elif resp['status_code'] == common_function.REDFISH_STATUS_CODE_400:
        print_err_fh(message)
    else:
        print("Failure: the request failed due to an internal service error")


def print_err_fh(message):
    """
    Function Description:print error message
    Parameter:message list:redfish interface value
    """
    messageid = message[0]['MessageId'].split('.')[-1]
    err_dict = {
        'EmergencyLoginUser':
            'Failure: the role cannot be modified '
            'because the user is an emergency login user',
        'AccountNotModified': 'Failure: failed to set the role',
        'PropertyModificationNeedPrivilege':
            'Failure: you do not have the required '
            'permissions to perform this operation'}
    message_info = "Failure: %s" % common_function.change_message(
        message[0]['Message'])
    print(err_dict.get(messageid), message_info)
