// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define([
    'fs/presenter/settings/NetworkSetupPresenter',
    'fs/view/settings/network/NetworkEditViewBase',
    'fs/view/settings/network/NetworkInterfaceTableView',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'fs/presenter/settings/AppliancePresenter',
    'hp/core/Notifications',
    'hp/model/Session',
    'fs/model/settings/ProductConfig',
    'hp/core/Localizer',
    'fs/view/settings/appliance/TrapDestinationsAddView',
    'fs/presenter/settings/ApplianceUpdatePresenter',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'jqueryUI',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpSearchCombo',
    'lib/jquery.dataTables',
    'lib/jquery-ui-timepicker-addon',
    'hp/lib/jquery-ui-timepicker-extension',
    'hp/lib/jquery.hpTimestamp',
    'lib/jquery.dateFormat'],
function( presenter, NetworkEditViewBase, NetworkInterfaceTableView, router, urlFragment,appliancePresenter,
        notifications,
        session, ProductConfig, Localizer,destinationAddView, applianceUpdatePresenter)
{"use strict";

    return ( function() {

        var OK = '#cic-settings-edit-ok',
            CANCEL = '#cic-settings-edit-cancel',
            SPINNER = '#cic-network-spinner',
            NOTIFY_BOX = '#cic-settings-details-notify',
            ROUTE_PREFIX = '/settings/edit/network',
            PANELS = '#cic-appliance-network-panel',
            PANEL_SELECTOR = '#cic-setting-network-panel-selector',
            FORM = '#cic-settings-network-form';

        var TRAP_TABLE = '#hp-trapdestinations';
        var ADD_DESTINATION = '#cic-trapdestination-add';
        var TRAP_FORWARD = '#cic-fsnetwork-panel-snmp';
        var SNMP_GLOBAL_CS = '#cic-snmp-globalcommunitystring';
        var SNMP = '.cic-fsnetwork-snmp';
        var NOTRAPDESTINATIONS = '#hp-snmp-edit-notrapdestinations';
        var TRAP_TABLE_WRAPPER = '#hp-snmp-edit-trapdestinations-container';

   var  MULTI_NIC_PANEL = "#fs-fsnetwork-panel-nics",
        HOSTNAME_PANEL  = "#cic-fsnetwork-panel-hostname",
        CLASS_NICS = ".fs-fsnetwork-nics";

    var TIME_LOCATION_PANEL = '#cic-fsnetwork-panel-timeandlanguage',
        NTP_SERVER_TEXT = '#cic-network-ntpserver',
        MANUAL_DATE_TIME_LABEL = '#cic-network-datetime-manual',
        CURRENT_DATE_TIME_TEXT = '#cic-network-currentdatetimeText',
        LOCALE = '#cic-network-locale',
        LOCALE_INPUT = '#cic-network-locale-input',
        NTP_SERVER = '.cic-network-ntpserver-group',
        CURRENT_DATE_TIME = '#cic-network-currentdatetime',
        CURRENT_DATE_TIME_TZSTRING = '#cic-datetime-tzstring',
        CURRENT_DATE_TIME_LABEL_GROUP = '#cic-network-currentdatetimelabel',
        CURRENT_DATE_TIME_LABEL_VALUE = '#cic-network-currentdatetimelabelValue',
        TIME_SYNC_SERVER ='#cic-network-syncwithserver',
        TIME_SYNC_MANUAL ='#cic-network-manualdatetime',
        HAS_ERROR = '#cic-network-form input.hp-error',
        TIME_AND_PLACE_CHOOSER ='timeandplacechooser',
        TIME_AND_PLACE_RADIO_GRP ='input[type="radio"][name='+TIME_AND_PLACE_CHOOSER+']:checked',
        DATETIME_WARNING = '#cic-datetime-warning',
        DATETIME_REBOOT_WARNING = '#cic-datetime-reboot-warning';


    var CURRENT_DATE_TIME_FORMAT='MMM d, yyyy hh:mm a',
        DATE_PICKER_FORMAT='yyyy-MM-dd HH:mm:ss',
        // product-config varibles
        PC_TIME_CHANGE_DISABLED_KEY = 'timeChangeDisabled',
        PC_REBOOT_ON_APPLIANCE_DATETIME_CHANGE = 'rebootOnTimeSet',
        PC_TIME_LOCATION_ON_EDITAPPLIANCE_DISABLED_KEY = 'timeAndLanguageOnEditApplianceDisabled',
        CLASS_TIMEANDLANGUAGE = '.cic-fsnetwork-timeandlanguage';

    var clickEventForSync = false;

    var localeList = [];

    var MAX_NTP_SERVERS_CONFIGURABLE = 3;
    var timers = [];
    var dateTimeUnixTS = {};
        dateTimeUnixTS.val = Date.parse(new Date());
    var clockUpdateTimeout = 1000;//ms
     var isManualSetting = true;

    var timeAndLanguageOnEditApplianceDisabled = false,
        timeChangeDisabled = false,
        rebootOnTimeChange = false;


        /**
         * @class View script for the Network Settings panel of the Edit Settings page.
         */
        function NetworkEditView() {

            var base = new NetworkEditViewBase();
            //var timeAndPlace = new TimeAndPlaceView();
            var networkInterfaceTableView = new NetworkInterfaceTableView();
            var trapTable;
            var taskName;
            //var destination; //commented for sonar unused var
            var deletedTrapResourceURIs = [];
            var deletedDestinations = [];
            var deletedDestinationStrs = [];
            var addedDestinations = [];
            var oldDestination = {"destination":"", "communityString":"", "port":""};
            var noUpdateFromServer = false; // this flag is used to indicate whether trap table is needed to refresh.
            var newForwardIndex = 1;
            var oldCommunityStr = "";
            var formStateView;

            function setControlsDisabled(disabledFlag) {
                 $(CANCEL).toggleClass('hp-disabled', disabledFlag);
                 $(OK).toggleClass('hp-disabled', disabledFlag);
            }

            /**
             * @private Set the active panel
             *
             */
            function changeLocation(location) {
                if (location.length > ROUTE_PREFIX.length) {
                    $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
                } else {
                    $(PANELS).hpStackedPanels('setFirstPanel');
                }
            }

           function onSelectionChange(selection) {
                urlFragment.replaceHrefUris(PANEL_SELECTOR, selection.uris);
                urlFragment.replaceHrefUris(CANCEL, selection.uris);
                $(PANELS).hpStackedPanels('setPanelByLocation',
                    '#' + router.location());
           }
            /**
             * @public On successful backend update redirect if needed or return
             *         to settings overview page
             */
            function onApplySuccess(redirect) {

                base.resetForm();
                setControlsDisabled(false);
                if (!redirect) {
                    $(CANCEL).trigger('click');
                }
            }
            /**
             * @public In case of backend error , remain on the current page
             */

            function onApplyError() {
//                setControlsDisabled(true);
              setControlsDisabled(false);
            }


            function onApplyRedirect(redirect) {
                if (redirect) {
                    base.dismissDialog();
                    onApplySuccess(true);
                } else {
                    base.dismissDialog();
                    if (presenter.shouldReloadWindow() ) {
                        window.location.reload();
                    }
                    onApplySuccess(false);
                }
            }

            /**
             * @private Re-validate the fields that are showing errors; leave
             * the fields without errors alone (so that we don't
             * display errors in them prematurely).
             */
            function resetFailures() {
                $(HAS_ERROR).each(function() {
                    validator.element(this);
                });
            }

            /**
             * @public Handle a click of the OK button by sending a REST request
             *         to set the new configuration
             */
            function apply() {

                if(!$(FORM).valid()) {
                    base.displayParameterError();
                    return;
                }
                setControlsDisabled(true);

                base.apply({ // Normal Flow
                      success: onApplyRedirect,
                          error: onApplyError
                  });
            }

            function showDateTime(data) {
                var dateVal = Date.parseISOString(data);
                dateTimeUnixTS.val = Date.parse(new Date(dateVal));
                if(isManualSetting){
                    var textdateVal = $.format.date(dateVal, DATE_PICKER_FORMAT);
                    $(CURRENT_DATE_TIME_TEXT).val(textdateVal);
                }else{
                    var labeldateVal = $.format.date(dateVal, CURRENT_DATE_TIME_FORMAT);
                    $(CURRENT_DATE_TIME_LABEL_VALUE).text(labeldateVal);
                }
                manageClock(true);
            }

            function fillNTPFields(ntpServerList){
                for(var index = 0;index < MAX_NTP_SERVERS_CONFIGURABLE;index = index+1){
                    $(NTP_SERVER_TEXT+(index+1)).val((ntpServerList[index]?ntpServerList[index]:''));
                }
            }

// private
            // adds a notification message to the queue
            function addNotification(message) {
                var notificationObj = {
                    summary : message
                };
                notifications.add(notificationObj, true);
            }

            //private
            // called after each row is rendered.
            function rowCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                var $nRow = $(nRow);
                $nRow.data('destination', aData.destination);
                $nRow.data('uri', aData.uri);
                return nRow;
            }

         // Displays an error in the Notifications view.  This is done by posting
            // a jQuery event that bubbles up the element stack to the SettingsView,
            // which owns the notifications area.
            function showError(error) {
                var errorMessage = {summary: error.errorMessage, status: 'error',
                        details: error.resolution};
                formStateView.setMessage(errorMessage);
                notifications.add(errorMessage, false);
            }

            function getLastestForwardIndex(trapDestination){
                var resourceURI = trapDestination.uri;
                var index = resourceURI.lastIndexOf("/");
                newForwardIndex = resourceURI.substring(index + 1, resourceURI.length);
                ++newForwardIndex;
            }

            function showTrapDestinations(trapDestinations)
            {
                trapTable.fnClearTable();
                var members = trapDestinations.members;
                trapTable.fnAddData(members);
                if(members.length > 0)
                {
                	$(TRAP_TABLE_WRAPPER).show();
                	$(NOTRAPDESTINATIONS).hide();
                    getLastestForwardIndex(members[members.length - 1]);
                    var updateMsg = Localizer.getString('fs.settings.appliance.snmp.updateMsg');
                    var updateDone = {
                        summary : updateMsg
                    };
                    notifications.add( updateDone, true);
                }
                else
                {
                    $(TRAP_TABLE_WRAPPER).hide();
                    $(NOTRAPDESTINATIONS).show();
                }

            }

            function updateTrapDestination()
            {
                appliancePresenter.getTrapDestinations({
                    success: showTrapDestinations,
                    error: showError
                });
            }

            function isDeletedRowInAddedDestinations(resourceURI)
            {
                var dest;
                for(var i = 0; i < addedDestinations.length; i++)
                {
                    dest = addedDestinations[i];
                    if(dest.uri === resourceURI)
                    {
                        addedDestinations.splice(i, 1);
                        return true;
                    }
                }

                return false;
            }

            function onTrapDestinationDeleteAction(ev) {
                var row = $(ev.currentTarget).parents('tr')[0];
                deletedTrapResourceURIs.push($(row).data('uri'));
                deletedDestinationStrs.push($(row).data('destination'));

                if(!isDeletedRowInAddedDestinations($(row).data('uri')))
                {
                    var destination = {};
                    destination.destination = $(row).data('destination');
                    destination.communityString = $(row).data('communityString');
                    destination.port = $(row).data('port');
                    destination.uri = $(row).data('uri');
                    deletedDestinations.push(destination);
                    trapTable.fnDeleteRow(row);
                }
                if (trapTable.fnGetData().length > 0)
                {
                    $(TRAP_TABLE_WRAPPER).show();
                    $(NOTRAPDESTINATIONS).hide();
                }
                else
                {
                    $(TRAP_TABLE_WRAPPER).hide();
                    $(NOTRAPDESTINATIONS).show();
                }
            }

            function onTrapDestinationDeletedSuccess(data)
            {
                updateTrapDestination();

            }

            function commitDeletedTrapDestinations()
            {
                if(deletedTrapResourceURIs.length > 0)
                {
                    var deletetrapDestinationMsg = Localizer.getString('fs.settings.appliance.snmp.deleteMsg', deletedDestinationStrs.join(" "));
                    taskName = session.getUser() + '-deleteTrapDestinationsTask-' + (new Date()).getTime();
                    var trapDestDeleteProgress = {
                        summary : deletetrapDestinationMsg,
                        uri : taskName,
                        progress : 0,
                        changing : true,
                        status : "info"
                    };
                    notifications.add( trapDestDeleteProgress, true);

                    deletedTrapResourceURIs.forEach(function (resourceURI) {
                        appliancePresenter.deleteTrapDestination(resourceURI, {
                            success: onTrapDestinationDeletedSuccess,
                            error: showError
                        });
                    });
                }
                deletedTrapResourceURIs = [];
                deletedDestinations = [];
                deletedDestinationStrs = [];
            }

            function onTrapDestinationAddedSuccess(data)
            {
                updateTrapDestination();
            }

            function commitAddedTrapDestinations()
            {
                if(addedDestinations.length > 0)
                {
                    addedDestinations.forEach(function (destination) {
                        appliancePresenter.addTrapDestination(destination.uri, destination, {
                            success: onTrapDestinationAddedSuccess,
                            error: showError
                        });
                    });
                }

                addedDestinations = [];
            }

            function onCommunityStringAddOrUpdatedSuccess()
            {
                var addCommunityStringMsg = Localizer.getString('fs.settings.appliance.snmp.addCSMsgSuccess', [$(SNMP_GLOBAL_CS).val()]);
                var csAddProgress = {
                    summary : addCommunityStringMsg
                };

                notifications.add( csAddProgress, false);
            }

            function commitGlobalCommunityString()
            {
                var csObject = {
                        communityString:$(SNMP_GLOBAL_CS).val()
                };

                applianceUpdatePresenter.addOrUpdateGlobalCommunityString(csObject, {
                    success: onCommunityStringAddOrUpdatedSuccess,
                    error: showError
                });
            }

            function onDestinationAdded(destination)
            {
                noUpdateFromServer = true;
                if(destination.destination !== oldDestination.destination
                        || destination.communityString !== oldDestination.communityString
                        || destination.port !== oldDestination.port)
                {
                	$(TRAP_TABLE_WRAPPER).show();
                    $(NOTRAPDESTINATIONS).hide();
                    addedDestinations.push(destination);
                    trapTable.fnAddData(destination);
                    getLastestForwardIndex(destination);
                    oldDestination = destination;
                }
            }

            function showGlobalCommunityString(data)
            {
                var localizedStr = Localizer.getString('fs.settings.appliance.snmp.publicStr');
                oldCommunityStr = data ? data.communityString : localizedStr;
                $(SNMP_GLOBAL_CS).val(oldCommunityStr);
            }

            function updateGlobalCommunityString()
            {
                applianceUpdatePresenter.getGlobalCommunityString({
                    success: showGlobalCommunityString,
                    error: showError
                });
            }

            /**
             * @private Initialization of trap forwarding destination table.
             */
            function trapTableInit()
            {
                trapTable = $(TRAP_TABLE).dataTable({
                    bPaginate : false,
                    bFilter: false,
                    bInfo : false,
                    bAutoWidth : false,
                    sScrollY: "400px",
                    bScrollCollapse: true,
                    aaData : [],
                    aoColumns :[
                        {mDataProp:'destination',
                            sWidth: 300,
                            sDefaultContent:''},
                        {mDataProp:'port',
                            sWidth: 100,
                            sDefaultContent:''},
                        {mDataProp:'communityString',
                             sWidth: 200,
                             sDefaultContent:''},
                        {mDataProp:'icon',
                             sTitle:"",
                             sWidth: 100,
                             sDefaultContent:'<div class="hp-delete" />'},
                        {mDataProp:'uri',
                             sWidth: 0,
                             sDefaultContent:'',
                             bVisible:false}
                    ],
                    fnRowCallback : rowCallback
                });

                updateTrapDestination();
                updateGlobalCommunityString();

                $(TRAP_TABLE).on('click', '.hp-delete', onTrapDestinationDeleteAction);

                $(ADD_DESTINATION).on('click', function(evt) {
                    //router.go('/settings/add/network/snmptrap','/settings/edit/network/snmp');
                    var args = {"newForwardIndex":newForwardIndex,
                    		    "trapTable":trapTable};
                    evt.preventDefault();
                    destinationAddView.showDialog(args);
                });
            }





            function showLocale(localeData)
            {
                var system_locale_name = localeData.displayName;
                var system_locale = localeData.locale;
                presenter.getLocales({
                    success: function(locales) {

                        $.each(locales.members, function (i, data) {
                            if ((data.locale != '') && (data.locale != null)) {
                                var tempObj = {id: data.locale, name: data.displayName, localeName: data.locale};
                                localeList[i] = tempObj;
                          }
                        });
                        // if length greater than 1 display hpSearchCombo else label
                        if (localeList.length > 1){
                            $(LOCALE).hpSearchCombo({results: localeList, maxResults: localeList.length});
                            // Set the current server locale to combo box.
                            $(LOCALE).hpSearchCombo('set', {id: system_locale, name: system_locale_name});
                            $(LOCALE_INPUT).attr('name', 'locale_input');
                        }else{
                            $(LOCALE).text(localeList[0].name);
                            $(LOCALE).val(localeList[0].localeName);
                        }
                    },
                    error: function (){
                }});
            }
            function checkNTPservers(data) {
                if( data.ntpServers.length > 0  ||  clickEventForSync ){
                    fillNTPFields(data.ntpServers);
                    $(TIME_SYNC_SERVER).attr('checked',true);
                    $(CURRENT_DATE_TIME_LABEL_GROUP).show();
                    isManualSetting = false;
                    getDateTime();
                    $(NTP_SERVER).show();
                    $(CURRENT_DATE_TIME).hide();
                    clickEventForSync=false;
                    $(DATETIME_WARNING).hide();
                }
                else{
                    $(TIME_SYNC_MANUAL).attr('checked',true);
                    $(NTP_SERVER).hide();
                    $(CURRENT_DATE_TIME_LABEL_GROUP).hide();
                    $(CURRENT_DATE_TIME).show();
                    $(CURRENT_DATE_TIME).val('');
                    if(!timeChangeDisabled){
                        $(DATETIME_WARNING).show();
                    }
                    isManualSetting = true;
                }
            }

            function showNTPservers(data) {
                fillNTPFields(data.ntpServers);
                checkNTPservers(data);
            }

            function  resetChange(){
              base.resetForm();
            }

            function registerEvents() {
              presenter.on("dateAndTimeChange", showDateTime);
              presenter.on("ntpServersChange", showNTPservers);
                presenter.on("localeChange", showLocale);
            }
            function removeEvents() {
              presenter.off("dateAndTimeChange", showDateTime);
              presenter.off("ntpServersChange", showNTPservers);
                presenter.off("localeChange", showLocale);
            }

            function getNTPservers() {
              presenter.getNTPservers();
            }

            function getDateTime() {
              presenter.getDateTime();
            }

            function showHideDateTimeSettings(){

                $('input:radio[name='+TIME_AND_PLACE_CHOOSER+']').click(function() {
                    if($(TIME_AND_PLACE_RADIO_GRP).attr('id') ==
                                     $(TIME_SYNC_MANUAL).attr('id')){
                          $(NTP_SERVER).hide();
                          $(NTP_SERVER_TEXT+1).rules('remove','required');
                          $(CURRENT_DATE_TIME_LABEL_GROUP).hide();
                          $(CURRENT_DATE_TIME).show();
                          $(CURRENT_DATE_TIME).val('');
                          $(DATETIME_WARNING).show();
                          isManualSetting = true;
                          // Todo:multinic enabled with size = 1
                          if(timeChangeDisabled ){
                              $(CURRENT_DATE_TIME_TEXT).prop("disabled", true);
                              $(DATETIME_WARNING).hide();
                          }
                          else {
                              $(CURRENT_DATE_TIME_TEXT).prop("disabled", false);
                              $(DATETIME_WARNING).show();
                          }
                      }
                      else
                      {
                          clickEventForSync = true;
                          $(CURRENT_DATE_TIME_LABEL_GROUP).show();
                          getNTPservers();
                          $(NTP_SERVER).show();
                          $(NTP_SERVER_TEXT+1).rules('add',{
                              required : true
                          });
                          $(CURRENT_DATE_TIME).hide();
                          $(DATETIME_WARNING).hide();
                          isManualSetting = false;
                      }
                    manageClock(true);
                    base.resetForm();
                  });
            }

            function initializeTimeAndLocation(){

                ProductConfig.getproductConfigMembers({
                    success : function(productConfigMembers) {
                        if(productConfigMembers[PC_TIME_LOCATION_ON_EDITAPPLIANCE_DISABLED_KEY] === 'true' )
                        {
                            timeAndLanguageOnEditApplianceDisabled = true;
                        }
                        if(productConfigMembers[PC_TIME_CHANGE_DISABLED_KEY] === 'true'){
                            timeChangeDisabled = true;
                        }
                          
                        if(productConfigMembers[PC_REBOOT_ON_APPLIANCE_DATETIME_CHANGE] === 'true'){
                            rebootOnTimeChange = true;
                        }
                        if(timeAndLanguageOnEditApplianceDisabled){
                            $(TIME_LOCATION_PANEL).hide();
                            $(CLASS_TIMEANDLANGUAGE).hide();
                        }
                        else {
                            $(TIME_LOCATION_PANEL).show();
                            $(DATETIME_REBOOT_WARNING).hide();
                            registerEvents();
                            $(NTP_SERVER).hide();
                            $(CURRENT_DATE_TIME_LABEL_GROUP).hide();
                            getNTPservers();
                            getDateTime();
                            showHideDateTimeSettings();

                            $(CURRENT_DATE_TIME_TEXT).datetimepicker({
                            timeFormat: 'HH:mm:ss',
                            dateFormat: 'yy-mm-dd'
                            });

                            $(CURRENT_DATE_TIME_TZSTRING).text(Date.tzOffsetString());
                            $(CURRENT_DATE_TIME_TZSTRING).clone().insertAfter($(CURRENT_DATE_TIME_LABEL_VALUE));

                            presenter.getLocale();

                            $(CURRENT_DATE_TIME_TEXT).change(function(){
                            dateTimeUnixTS.val = Date.parse(new Date(presenter.parseDateTime($(CURRENT_DATE_TIME_TEXT).val())));
                            base.setDateTimeChangeFlag(true);
                            });


                            resetFailures();
                            if(timeChangeDisabled ){
                                $(CURRENT_DATE_TIME_TEXT).prop("disabled", true);
                                $(DATETIME_WARNING).hide();
                                var synchronizeWithVMHostLabel = Localizer.getString('fs.settings.network.fields.manualdatetime.synchronizeWithHost');
                                $(MANUAL_DATE_TIME_LABEL).text(synchronizeWithVMHostLabel);
                            }
                            else {
                                $(CURRENT_DATE_TIME_TEXT).prop("disabled", false);
                                if(rebootOnTimeChange){
                                    $(DATETIME_WARNING).hide();
                                    DATETIME_WARNING = DATETIME_REBOOT_WARNING ;
                                }
                                $(DATETIME_WARNING).show();
                            }
                        }
                    }
                });
                
                      
            }
            /**
             * @private
             * @param on Boolean value indicating whether clock
             *           should be enabled or not
             */
            function manageClock(on){
                var updateDateTimeField;
                if(isManualSetting){
                    clockUpdateTimeout = 1000;
                    updateDateTimeField = function(d){
                        $(CURRENT_DATE_TIME_TEXT).val($.format.date(d, DATE_PICKER_FORMAT));
                        if($(CURRENT_DATE_TIME_TEXT).is(':focus')){
                            $(CURRENT_DATE_TIME_TEXT).datepicker('updatePicker',d);
                        }
                    };
                }else{
                    clockUpdateTimeout = 60000;
                    updateDateTimeField = function(d){
                        $(CURRENT_DATE_TIME_LABEL_VALUE).text($.format.date(d, CURRENT_DATE_TIME_FORMAT));
                    };
                }
                Date.registerClock(on,{
                    timerList:timers,
                    dateTimeFieldHandler:updateDateTimeField,
                    timeout:clockUpdateTimeout,
                    dateTimeUTS:dateTimeUnixTS
                    });
            }
            /**
             * @private Screen loader method
             * @param {display} Boolean flag to display/hide screen elements 
             */
            function showScreen(display){
                if(display){
                    $(SPINNER).hide();
                    $(PANEL_SELECTOR).show();
                    $(FORM).show();
                }else{
                    $(PANEL_SELECTOR).hide();
                    $(FORM).hide();
                    $(SPINNER).show();
                }
            }

            /**
             * @public Initialization method
             */
            this.init = function() {
                 showScreen(false);
                 if(presenter.trapForwardingDisabled()) {
                     $(TRAP_FORWARD).remove();
                     $(SNMP).remove();
                 }
                 else{
                     trapTableInit();
                     destinationAddView.init();
                 }
                //registerTimeAndPlaceEvents();
                base.setFirstTime(false);
                base.setApplianceMoreView(false);
                presenter.on("selectionChange", onSelectionChange);
                $(HOSTNAME_PANEL).show();

                base.init(ROUTE_PREFIX, FORM, {
                    success: function(){
                        $(PANELS).hpStackedPanels({
                            panelSelector : PANEL_SELECTOR
                        });
                        router.watch('appliance network section', ROUTE_PREFIX + '.*',
                                {parent: ROUTE_PREFIX, change: changeLocation});
                        showScreen(true);
                        base.updateNTPFieldRules();
                    }
                });
                //timeAndPlace.init();
                // pass the form state view to Time and place
                //timeAndPlace.setFormStateViewInstance(base.getFormStateViewInstance());
                formStateView = base.getFormStateViewInstance();

                $(MULTI_NIC_PANEL).hide();
                $(CLASS_NICS).hide();

                var validCommunityString = Localizer.getString('fs.settings.appliance.snmp.validateCommunityString');
                $.validator.addMethod("hpSettingsSnmpGlobalCommunityString", function(value, element, param) {
                    return value.length > 0;
                }, validCommunityString);

                var validatorOptions = {
                        rules : {
                            required : true,
                            globacommunitystring : {
                                hpSettingsSnmpGlobalCommunityString: SNMP_GLOBAL_CS
                            }
                        }
                };

                base.addNicsValidatorOptions(validatorOptions);
                var validator =  $(FORM).validate(validatorOptions);
                base.setValidator(validator);
                base.setNotifyElement($(NOTIFY_BOX));

                getConfiguredNICs();
                // Handlers for the buttons.
                $(OK).on('click', function(ev) {
                    if ( $(OK).hasClass('hp-disabled') ){
                        return false;
                    } else {

                        if(!(presenter.trapForwardingDisabled())){
                            commitDeletedTrapDestinations();
                            commitAddedTrapDestinations();
                            commitGlobalCommunityString();
                        }
                        noUpdateFromServer =  true;
                        apply(true);
                        ev.preventDefault();
                    }
                });

                $(CANCEL).on('click', function(ev) {
                    if ( $(CANCEL).hasClass('hp-disabled') ){
                        return false;
                    } else {
                    	$('#cic-network-hostname').removeClass("hp-error");
                        base.resetForm();
                        if(!(presenter.trapForwardingDisabled())){
                            if(oldCommunityStr.length > 0)
                            {
                                $(SNMP_GLOBAL_CS).val(oldCommunityStr);
                            }
                            else{
                                $(SNMP_GLOBAL_CS).val(
                                        Localizer.getString('fs.settings.appliance.snmp.publicStr'));
                            }

                            updateTrapDestination();
                        }

                        addedDestinations = [];
                        deletedTrapResourceURIs = [];
                        deletedDestinations = [];
                        deletedDestinationStrs = [];
                        return true;
                    }

                });

                $(NOTIFY_BOX).fadeOut();

                appliancePresenter.addDestinationHandler(onDestinationAdded);

                //Time and place panel
                initializeTimeAndLocation();
                //Time and place panel ends


            };

            this.pause = function() {
                 presenter.off("selectionChange", onSelectionChange);
                 $(PANELS).hpStackedPanels('pause');
                 removeEvents();
                 manageClock(false);

            };
            /**
             * @public IWhen re-enter the page make sure to reset the form
             * and re-obtain the data
            */
            this.resume = function() {
               showScreen(false);
               base.resetForm(FORM);
               base.setApplianceMoreView(false);
               presenter.on("selectionChange", onSelectionChange);
               base.resume({
                   success: function(){
                       $(PANELS).hpStackedPanels('resume');
                       showScreen(true);
                       changeLocation("");
                       base.updateNTPFieldRules();
                   }
               });
               getConfiguredNICs();
               resetFailures();
               registerEvents();
               getNTPservers();
               presenter.getLocale();
               getDateTime();
               // The following block is for trap forwarding
               deletedTrapResourceURIs = [];
               deletedDestinations = [];
               deletedDestinationStrs = [];
               if (!(presenter.trapForwardingDisabled())){
                   if (!noUpdateFromServer)
                   {
                       updateTrapDestination();
                   }
                   updateGlobalCommunityString();
               }
            };

            function getConfiguredNICs(){
             presenter.getConfiguredNICs({
                success: function(multiNicDTO) {
                    $.each( multiNicDTO.applianceNetworks, function( key, value ) {
                         var interfaceTypeVal = '';
                         if(value.device == 'eth0')
                         {
                          networkInterfaceTableView.setPrimaryNetworkObj(this);
                          base.setPrimaryNetworkObj(this);
                          interfaceTypeVal = 'Primary';
                          base.setFormLayout(this);
                          base.fillFields(this);
                          }
               	    });
                    if (multiNicDTO.serverCertificate != null) {
                        base.setServerCertificate(multiNicDTO.serverCertificate);
                    }
                },
                error: base.onError
             });
            }

            this.addValidatorOptions = base.addValidatorOptions;
        }

        return new NetworkEditView();
    }());
});
