# -*- coding:utf-8 -*-
"""
Function: set_community_name.py moudle. This moudle mainly involves the
set community name function.
Copyright Information: xFusion Digital Technologies Co.,
 Ltd. All Rights Reserved © 2022-2022
"""
from scripts import common_function


INVALID_VALUE = None


def setcommunityname_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    set community name
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setcommunityname',
                                   help='''set community name''')
    sub_parser.add_argument('-N', dest='communityName', required=False,
                            help='''set community name''')
    parser_dict['setcommunityname'] = sub_parser
    return 'setcommunityname'


def setcommunityname(client, args):
    """
    Function Description:set community name
    Parameter:client refishClient: class object
    args object:CLI command
    """
    slot_id = client.get_slotid()
    if slot_id is None:
        return INVALID_VALUE
    url = "/redfish/v1/Managers/%s/SnmpService" % slot_id
    resp = client.get_resource(url)
    if resp is None:
        return INVALID_VALUE
    if resp['status_code'] != 200:
        if resp['status_code'] == 404:
            common_function.print_info('Failure: resource was not found')
        return resp
    # Request body\
    payload = {
        "SnmpV2CEnabled": True,
        "SnmpTrapNotification": {
            "ServiceEnabled": True,
            "TrapVersion": "V2C",
            "TrapV3User": "Administrator",
            "TrapMode": "OID",
            "TrapServerIdentity": "HostName",
            "CommunityName": args.communityName,
            "AlarmSeverity": "Normal"
        }
    }
    resp = client.set_resource(url, payload)
    if resp is None:
        return INVALID_VALUE
    if resp['status_code'] == 200:
        common_function.print_info('The command succeed to run')
    # Error message response message
    else:
        message = resp['message']['error']['@Message.ExtendedInfo']
        messageid = message[0]['MessageId'].split('.')[-1]
        if messageid == "OperationNotSupported":
            common_function.print_info("Failure: this operation is not supported")
        else:
            common_function.print_info("Failure: " + change_message(message[0]['Message']))
    return resp


def change_message(messageinfo):
    if (messageinfo[0] >= 'A' and messageinfo[0] <= 'Z') and (messageinfo[-1] == '.'):
        return messageinfo[0].lower() + messageinfo[1:-1]
    return messageinfo

