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


def getrole_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    Querying Role Information
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('getrole',
                                   help='''get role information''')
    sub_parser.add_argument('-R', dest='role',
                            required=False,
                            choices=['Administrator', 'Operator',
                                     'Commonuser', 'NoAccess', 'CustomRole1',
                                     'CustomRole2', 'CustomRole3',
                                     'CustomRole4'],
                            help='''role ID''')

    parser_dict['getrole'] = sub_parser

    return 'getrole'


def getrole(client, args):
    """
    Function Description:Querying Role Information
    Parameter:client refishClient: class object
    args object:CLI command
    """
    url = "/redfish/v1/AccountService/Roles"

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

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

    resp = get_role_info(client, resp, args)
    return resp


def get_role_info(client, resp, args):
    """
    Function Description:get role information
    Parameter:client refishClient: class object
    resp dict: redfish interface value
    args object:CLI command
    """
    if args.role is None:
        print('-' * 80)
        for role_id in resp['resource']['Members']:
            url = role_id['@odata.id']
            role_resp = client.get_resource(url)
            if role_resp is None:
                return None
            if role_resp['status_code'] != REDFISH_STATUS_CODE_200:
                error_message(role_resp)
                return None

            print_resource(role_resp['resource'])

    else:
        for role_id in resp['resource']['Members']:
            url = role_id['@odata.id']
            role_resp = client.get_resource(url)
            if role_resp is None:
                return None
            if role_resp['status_code'] != REDFISH_STATUS_CODE_200:
                error_message(role_resp)
                return role_resp

            if args.role.lower() == role_resp['resource']['Id'].lower():
                print('-' * 80)
                print_resource(role_resp['resource'])
                return role_resp

        print('Failure: the role does not exist')

    return resp


def print_resource(info):
    """
    Function Description:print resource
    Parameter:info dict: redfish interface value
    """
    print("%-18s%-2s%-s" % ('Role', ":", info.get('Id', '')))
    print("%-18s%-2s%-s" % ('IsPredefined', ":", info.get('IsPredefined', '')))

    oemprivileges = []
    for privileges in info['OemPrivileges']:
        oemprivileges.append(privileges.replace('Oem', ''))

    if oemprivileges:
        pri_str = ','.join(info.get('AssignedPrivileges', '')) + \
                  ',' + ','.join(oemprivileges)
    else:
        pri_str = ','.join(info.get('AssignedPrivileges', ''))

    len_pri = len(pri_str)
    if len_pri == 0:
        print("%-18s%-2s%-s" % ('Privileges', ":", None))
    else:
        print("%-18s%-2s%-s" % ('Privileges', ":", pri_str))

    print('-' * 80)


def error_message(resp):
    """
    Function Description:print error message
    Parameter:info dict: redfish interface value
    """
    if resp['status_code'] == REDFISH_STATUS_CODE_404:
        print('Failure: resource was not found')
    elif resp['status_code'] == REDFISH_STATUS_CODE_400:
        print("Failure: the request failed due to an internal service error")
