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

INVALID_VALUE = None


def setsnmptrap_init(parser, parser_dict):
    """
    Function Description:initializing the Command for
    set snmp trap
    Parameter:parser object: action object
    parser_dict dict: dictionary format of subcommand and ArgumentParser
    """
    sub_parser = parser.add_parser('setsnmptrap',
                                   help='''set community name''')
    sub_parser.add_argument('-V', dest='version', required=False,
                            help='''set trap version''')
    sub_parser.add_argument('-M', dest='model', required=False,
                            help='''set trap model''')
    sub_parser.add_argument('-S', dest='identity', required=False,
                            help='''set trap server identity''')
    sub_parser.add_argument('-L', dest='level', required=False,
                            help='''set alarm level''')
    sub_parser.add_argument('-A', dest='address', required=False,
                            help='''set server address''')
    sub_parser.add_argument('-E', dest='address_enabled', type=str, required=False, choices=['True', 'False'],
                            help='''set server address status True/False''')
    sub_parser.add_argument('-BE', dest='address_bob_enabled', type=str, required=False, choices=['True', 'False'],
                            help='''set address bob enable status True/False''')
    parser_dict['setsnmptrap'] = sub_parser
    return 'setsnmptrap'


def setsnmptrap(client, args):
    """
    Function Description:set snmp trap
    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
    trap_version = args.version if args.version else "V2C"
    trap_mode = args.model if args.model else "PreciseAlarm"
    trap_server_identity = args.identity if args.identity else "BoardSN"
    alarm_severity = args.level if args.level else "Critical"
    trap_server = get_trap_server(args.address, args.address_enabled, args.address_bob_enabled)
    if len(trap_server) > 4:
        common_function.print_info("Failure:Only four server addresses can be set")
        return INVALID_VALUE
    payload = {
        "SnmpV2CEnabled": True,
        "SnmpTrapNotification": {
            "ServiceEnabled": True,
            "TrapVersion": trap_version,
            "TrapMode": trap_mode,
            "TrapServerIdentity": trap_server_identity,
            "AlarmSeverity": alarm_severity,
            "TrapServer": trap_server
        }
    }
    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 get_trap_server(address, enabled_flag, bob_enabled_flag):
    trap_server = []
    if not address:
        return trap_server
    if "," not in address:
        params = {"TrapServerAddress": address}
        if enabled_flag is not None:
            params["Enabled"] = enabled_flag == str(True)
        if bob_enabled_flag is not None:
            params["BobEnabled"] = bob_enabled_flag == str(True)
        trap_server.append(params)
    else:
        ip_list = address.split(",")
        for ip in ip_list:
            params = {"TrapServerAddress": ip}
            if enabled_flag is not None:
                params["Enabled"] = enabled_flag == str(True)
            if bob_enabled_flag is not None:
                params["BobEnabled"] = bob_enabled_flag == str(True)
            trap_server.append(params)
    return trap_server


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