// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/presenter/settings/AppliancePresenter',
        'hp/core/Localizer',
        'hp/model/Session',
        'hp/core/Notifications',
        'hp/view/FormStateView',
        'hp/view/DialogView',
        'text!fsPages/settings/network/addTrapDestination.html',
        'jquery',
        'lib/jquery.validate' ],
function(presenter, Localizer, session, notifications, FormStateView,
        DialogView, destinationDialogHtml) { "use strict";

    var TrapDestinationsAddView = (function() {
        var FORM = '#cic-trapdestination-add-form',
        ADDAGAIN = "#cic-trapdestination-add-again",
        TRAPDESTINATION = '#cic-snmp-add-trapdestination',
        PORT = '#cic-snmp-port',
        COMMUNITYSTRING = '#cic-snmp-communitystring',
        MAX_COMMUNITYSTRING_LENGTH = 20,
        CANCEL = '#cic-trapdestination-add-cancel';

    var DEFAULT_PORT = "162",
        DEFAULT_COMMUNITY_STRING = "public";
    var trapTable;

        /**
         * Constructor
         */
        function TrapDestinationsAddView() {

            var validator;
            var taskName;
            var addAgain = false;
            var twoRoles = false;
            var formStateView = new FormStateView();
            var numberOfClicks = 0;
            var newForwardIndex = 1;

            /**
             * @private
             */
            function showError(error) {
                var errorMessage =
                  {summary: Localizer.getString('fs.settings.appliance.snmp.unableToAddTrapDestination'),
                   status: 'error',
                   errorMessage: {errorMessage:error.errorMessage,
                	              resolution:error.resolution}
                   };
                formStateView.setMessage(errorMessage);
            }

            /**
             * @private
             */
            function reset() {
                numberOfClicks = 0;
                validator.resetForm();
                formStateView.reset();
                $(TRAPDESTINATION).val("");

                if (addAgain){
                    $(TRAPDESTINATION).focus();
                }
            }

            function showTrapDestinations(trapDestinations)
            {
                var members = trapDestinations.members;
                if(members.length > 0)
                {
                    var destination = members[members.length - 1];
                    var resourceURI = destination.uri;
                    var index = resourceURI.lastIndexOf("/");
                    newForwardIndex = resourceURI.substring(index + 1, resourceURI.length);
                    ++newForwardIndex;
                }
            }

            function updateTrapDestination()
            {
                presenter.getTrapDestinations({
                    success: showTrapDestinations,
                    error: function(errorMessage){
                        var notifMsg = Localizer.getString('fs.settings.appliance.snmp.retrieveDestinationsfailure');
                        var trapRetrieve = {
                            summary : notifMsg
                        };
                        notifications.add(trapRetrieve, true);
                    }
                });
            }

            function getDestinationObject()
            {
            	return {
                        destination:$(TRAPDESTINATION).val(),
                        communityString:$(COMMUNITYSTRING).val(),
                        port:$(PORT).val(),
                        uri:"/rest/appliance/trap-destinations/" + newForwardIndex
                };
            }

            function onHostnameValidationSuccess() {
                var destination = getDestinationObject();
                presenter.addDestination(destination);

                if (!addAgain) {
                    $(CANCEL).trigger('click');
                }
                else
                {
                	reset();
                }
            }

            function validateDuplicate(destinationValue)
            {
                if(trapTable)
                {
                	var length = trapTable.fnGetData().length;
                    for (var i = 0; i < length; i++)
                    {
                        if(trapTable.fnGetData(i).destination === destinationValue.destination)
                        {
                        	return true;
                        }
                    }
                 }

                 return false;
             }


            /**
             * @private
             */
            function onAddTrapDestinationClick(fromAddAgain) {
                var returnValue = $(FORM).valid();
                if (returnValue) {
                    numberOfClicks = numberOfClicks + 1;
                    var notifMsg = Localizer.getString('fs.settings.appliance.snmp.addMsg',[$(TRAPDESTINATION).val()]);

                    if(numberOfClicks === 1){
                        taskName = session.getUser() + '-addTrapDestinationTask-' + (new Date()).getTime();
                    }
                    var trapDestAddBegin = {
                        summary : notifMsg,
                        uri : taskName,
                        progress : 0,
                        changing : true,
                        status : "info"
                    };
                    notifications.add(trapDestAddBegin, true);
                    if(fromAddAgain !== true)
                    {
                        addAgain = false;
                    }

                    ++newForwardIndex;
                    var destination = getDestinationObject();
                    if(!validateDuplicate(destination))
                    {
                        presenter.validateHostname(destination, {
                            success: onHostnameValidationSuccess,
                            error: showError
                        });
                    }
                    else
                    {
                    	showError({errorMessage:Localizer.getString('fs.settings.appliance.snmp.unabletoconfiguredestination')
                                  + destination.username
                                  + Localizer.getString('fs.settings.appliance.snmp.isdestinationconfigured'),
                                  resolution:Localizer.getString('fs.settings.appliance.snmp.specifyanotherdestination')});
                    }
                }

                return false;
            }


            /**
             * @private
             */
            function initForm() {
                var validTrapDestination = Localizer.getString('fs.settings.appliance.snmp.validateHostAddress');
                var validPort = Localizer.getString('fs.settings.appliance.snmp.validatePortNumber');
                $.validator.addMethod("hpSettingsSnmpPortNumber", function
                        (value, element, param) {
                    return value >= 1 && value <=65535;
                }, validPort);

                /*$.validator.addMethod("hpSettingsDestination", function
                        (value, element, param) {
                    return $(TRAPDESTINATION).val().length > 0;
                }, validTrapDestination);*/

                validator = $(FORM).validate({
                    onkeyup: false,
                    rules : {
                        /*trapdestination : {
                            hpSettingsDestination: TRAPDESTINATION,
                            hostAddress : ['hostname', 'ipv4']
                        },*/
                    	messages: {
                    		trapdestination: validTrapDestination
                        },
                        port : {
                            required : true,
                            number : true,
                            hpSettingsSnmpPortNumber : PORT
                        },
                        communitystring : {
                            required : true,
                            maxlength: MAX_COMMUNITYSTRING_LENGTH
                        }
                    },
                    errorPlacement : function(error, element){
                        error.insertAfter(element);
                    }
                });

                $(TRAPDESTINATION).focus();

            }

            this.showDialog = function (args) {
                var dialog;
                var contents = $(destinationDialogHtml);
                newForwardIndex = args.newForwardIndex;
                trapTable = args.trapTable;
                addAgain = false;
                dialog = new DialogView({contents: contents,
                    ok: onAddTrapDestinationClick,
                    cancel: function () {
                        addAgain = false;
                        validator.resetForm();
                    }
                });
                $(ADDAGAIN).click(function(ev) {
                    addAgain = true;
                    onAddTrapDestinationClick(true);
                    ev.preventDefault();
                });
                formStateView.init({form: FORM,
                    autoTrack: true});
                initForm();
                // This line make form state become smaller in order to avoid
                // overlap Add button.
                $('#hp-form-state').css("width", 1060);
                numberOfClicks = 0;
                validator.resetForm();
                $(TRAPDESTINATION).val("");
                $(PORT).val("162");
                $(COMMUNITYSTRING).val("public");
            }
            /**
             * @public
             */
            this.init = function() {

                updateTrapDestination();


            };
        }

        return new TrapDestinationsAddView();
    }());

    return TrapDestinationsAddView;
});
