// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/presenter/settings/NetworkSetupPresenter',
        'fs/view/settings/network/NetworkEditViewBase',
        'fs/view/settings/network/NetworkInterfaceTableView',
        'fs/presenter/settings/AppliancePresenter',
        'hp/core/Localizer',
        'hp/core/Router',
        'fs/view/settings/backup/BackupStatusView',
        'fs/view/common/CommonDisplayView',
        'hp/model/Session',
        'jquery',
        'lib/jquery.dataTables',
        'lib/jquery.dateFormat',
        'hp/lib/jquery.hpStackedPanels',
        'hp/lib/jquery.hpTimestamp'],
function(networkPresenter, NetworkEditViewBase, NetworkInterfaceTableView,appliancePresenter,
        localizer, router,  
        backupStatusView,commonDisplayView, session) { "use strict";

    var ApplianceMoreView = (function() {
    
        var base = new NetworkEditViewBase();
        
        var networkInterfaceTableView = new NetworkInterfaceTableView();

        var CLASS_PREFIX = '.fs-settings-appliance',
            CLASS_VALUE = CLASS_PREFIX + '-value',
            CLASS_1NODE = CLASS_PREFIX + '-1node',
            CLASS_2NODE = CLASS_PREFIX + '-2node',
            CLASS_IPV6 = CLASS_PREFIX + '-IPv6',
            CLASS_HARDWARE = CLASS_PREFIX + '-hardware',
            CLASS_IPV4_DHCP = CLASS_PREFIX + '-IPv4-DHCP',
            CLASS_IPV6_DHCP = CLASS_PREFIX + '-IPv6-DHCP';

        var ID_PREFIX = CLASS_PREFIX.replace('.', '#'),
            GENERAL_PREFIX = ID_PREFIX + '-general',
            MODEL = GENERAL_PREFIX + '-model',
            SERIAL = GENERAL_PREFIX + '-serial',
            VERSION = GENERAL_PREFIX + '-version',
            DATE = GENERAL_PREFIX + '-date';

        var PANELS = ID_PREFIX + '-panels',
            PANEL_SELECTOR = '#hp-settings-panel-selector',
            ROUTE_PREFIX = '/settings/show/appliance/(general|networks|timeandlanguage|backup|snmp)',
            UNAVAILABLE = 'hp-unavailable',
            ADD_NOTIFICATION = 'addNotification';

        var CLASS_IPV6_DISABLE = '.fs-settings-ipv6-remove';

        var CURRENT_DATE_TIME = '#fs-settings-appliance-timeandlanguage-currentdatetime',
            NTP_SERVER = '#fs-settings-appliance-timeandlanguage-ntpserver',
            NTP_SERVER_LIST = '#fs-settings-appliance-timeandlanguage-list-ntpserver',
            LOCALE = '#fs-settings-appliance-timeandlanguage-locale';

        var MAX_NTP_SERVERS_LISTED = 3;
        var TRAP_TABLE = '#hp-trapdestinations';
        var NOTRAPDESTINATIONS = '#hp-show-notrapdestinations';
        var TRAP_FORWARD = '#fs-settings-appliance-snmp';
        var SNMP_MENU = '#fs-settings-appliance-snmp-selector';
        var SNMP_GLOBAL_CS = '#fs-settings-appliance-snmp-globalcommunitystring';
        
        var  MULTI_NIC_PANEL = "#fs-fsnetwork-panel-nics",
             CLASS_NICS = ".fs-fsnetwork-nics",
             FORM = "#fs-appliance-more-form";
            
        /**
         * Constructor
         */
        function ApplianceMoreView() {
            var canReadCommunity;
            var canReadTrapDest;
            var trapTable;
            var timers = [];
            var dateTimeUnixTS = {},
                clockUpdateTimeout = 60000;//ms

            // 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) {
                $(PANELS).trigger(ADD_NOTIFICATION, {
                    summary: error.errorMessage,
                    details: error.resolution,
                    status: 'error'
                }, true);
            }

            

            // Display the appliance version data (called when it is received from the server).
            function showApplianceVersion(data) {
                // Show the model number.
                // REVISIT: the back end is not currently generating a modelNumber field; it generates
                // hardwareModel.  But VMs will have model numbers too, so this will change.
                if (data.modelNumber) {
                    $(MODEL).text(data.modelNumber).removeClass(UNAVAILABLE);
                } else if (data.platformType == 'vm') {
                    $(MODEL).text(localizer.getString('fs.settings.appliance.platform.vm')).removeClass(UNAVAILABLE);
                } else if (data.hardwareModel) {
                    $(MODEL).text(data.hardwareModel).removeClass(UNAVAILABLE);
                }

                // Show the serial number.
                // REVISIT: the back end is not generating a serialNumber field right now.
                if (data.platformType == 'hardware') {
                    $(CLASS_HARDWARE).show();
                    if (data.serialNumber) {
                        $(SERIAL).text(data.serialNumber).removeClass(UNAVAILABLE);
                    }
                }

                // Show version number.
                $(VERSION).text(data.softwareVersion).removeClass(UNAVAILABLE);

                // Show the version date.
                var date = Date.parseISOString(data.date);
                date = $.format.date(date, 'MMM d, yyyy');
                // REVISIT:  Need to internationalize the date format.
                $(DATE).text(date).removeClass(UNAVAILABLE);
            }

            

            function showTrapDestinations(trapDestinations)
            {
                if(canReadTrapDest)
                {
                    trapTable.fnClearTable();
                    var members = trapDestinations.members;
                    if(members.length > 0)
                    {
                        trapTable.fnAddData(members);
                        $(TRAP_TABLE).show();
                        $(NOTRAPDESTINATIONS).hide();
                    }
                    else
                    {
                        $(TRAP_TABLE).hide();
                        $(NOTRAPDESTINATIONS).show();
                    }
                }
				
                $(PANELS).hpStackedPanels('reset');
            }

            function showGlobalCommunityString(data){
                if(canReadTrapDest){
                    if(data){
                        $(SNMP_GLOBAL_CS).text(data.communityString);
                    }
                    else{
                        $(SNMP_GLOBAL_CS).text(localizer.getString('fs.settings.appliance.snmp.publicStr'));
                    }
                }
            }

            // Retrieve the appliance software version and platform type from the server.
            function getApplianceData() {
                appliancePresenter.getVersion({
                    success: showApplianceVersion,
                    error: showError
                });
                if(!(networkPresenter.trapForwardingDisabled())){
                    if(canReadTrapDest){
                        appliancePresenter.getTrapDestinations({
                            success: showTrapDestinations,
                            error: showError
                        });
                    }

                    if(canReadCommunity){
                        appliancePresenter.getGlobalCommunityString({
                            success: showGlobalCommunityString,
                            error: showError
                        });
                    }
                }
            }

            function changeLocation(location) {
                $(PANELS).hpStackedPanels('setPanelByLocation', '#' + location);
            }
            /**
             * @private
             * @param on Boolean value indicating whether clock
             *           should be enabled or not
             */
            function manageClock(on){
                Date.registerClock(on,{
                    timerList:timers,
                    dateTimeUTS:dateTimeUnixTS,
                    dateTimeFieldHandler:function(d){
                        $(CURRENT_DATE_TIME).text($.format.date(d, 'MMM d, yyyy hh:mm a')+Date.tzOffsetString());
                    },
                    timeout:clockUpdateTimeout
                });
            }
            function showDateTime(data) {
                var dateVal = Date.parseISOString(data);
                dateTimeUnixTS.val = Date.parse(new Date(dateVal));
                manageClock(true);
                dateVal = $.format.date(dateVal, 'MMM d, yyyy hh:mm a');
                $(CURRENT_DATE_TIME).text(dateVal+Date.tzOffsetString()).removeClass(UNAVAILABLE);
                $(PANELS).hpStackedPanels('reset');
            }
            function showNTPservers(ntpData) {
                //hide NTPServer 2,3,.. list elements
                $('.ntpserver-list').hide();

                if(ntpData.ntpServers.length > 0){
                    $.each(ntpData.ntpServers, function(index, element){
                        if(index < MAX_NTP_SERVERS_LISTED){
                            if(index===0){
                                $(NTP_SERVER).text(ntpData.ntpServers[index]).removeClass(UNAVAILABLE);
                            }else{
                                //check if NTP list element has already been added
                                if($(NTP_SERVER+(index+1)).length === 0){
                                    var listElement = $(NTP_SERVER_LIST).clone().attr('id',NTP_SERVER_LIST.slice(1)+(index+1));
                                    listElement.attr('class','ntpserver-list');
                                    listElement.children('label').removeAttr('data-localize').attr('for',NTP_SERVER.slice(1)+(index+1)).text('');
                                    listElement.children('div').attr('id',NTP_SERVER.slice(1)+(index+1)).text(element.toString());
                                    listElement.insertAfter(NTP_SERVER_LIST+(((index-1)===0)?'':(index)));
                                }else{
                                    $(NTP_SERVER+(index+1)).text(element.toString()).removeClass(UNAVAILABLE);
                                    $(NTP_SERVER_LIST+(index+1)).show();
                                }
                            }
                        }
                    });
                }else{
                    $(NTP_SERVER).text(localizer.getString('fs.settings.appliance.timeandlanguage.ntpnotconfigured')).removeClass(UNAVAILABLE);
                }
                $(PANELS).hpStackedPanels('reset');
            }

            function showLocale(localeData) {
                $(LOCALE).text(localeData.displayName).removeClass(UNAVAILABLE);
                $(PANELS).hpStackedPanels('reset');
            }

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

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

            function getDateTime() {
                networkPresenter.getDateTime();
            }
            function getNTPservers() {
                networkPresenter.getNTPservers();
            }
            function getLocale() {
                networkPresenter.getLocale();
            }

            function trapTableInit()
            {
                trapTable = $(TRAP_TABLE).dataTable({
                    bPaginate : false,
                    bFilter: false,
                    bInfo : false,
                    bAutoWidth : false,
                    aoColumns :[
                        {mDataProp:'destination', sWidth: 300, sDefaultContent:''},
                        {mDataProp:'port', sWidth: 100, sDefaultContent:''},
                        {mDataProp:'communityString', sWidth: 200, sDefaultContent:''}
                    ]
                });
            }
               
            
            
            this.init = function() {
                canReadTrapDest = session.canPerformAction('trapforwarding', 'Read');
                canReadCommunity = session.canPerformAction('communitystring','Read');

                if(networkPresenter.trapForwardingDisabled() || !canReadTrapDest)
                {
                    $(TRAP_FORWARD).remove();
                    $(SNMP_MENU).remove();
                }
                else{
                    trapTableInit();
                }
                base.setFirstTime(false);
                base.setApplianceMoreView(true);
                
                base.init(ROUTE_PREFIX, FORM, {
                    success: function(){
                        
                    },error: function(){
                        
                    }
                });
                $(PANELS).hpStackedPanels({
                    panelSelector : PANEL_SELECTOR
                });
                $(MULTI_NIC_PANEL).hide(); 
                $(CLASS_NICS).hide();
                router.watch('settings show appliance section', ROUTE_PREFIX + '.*',
                    {parent: ROUTE_PREFIX, change: changeLocation});
                registerEvents();
                if (networkPresenter.iPv6Disabled()) {
                   $(CLASS_IPV6_DISABLE).remove();
                }
                $(CLASS_VALUE).addClass('hp-unavailable').empty();
                $(CLASS_1NODE).show();
                $(CLASS_HARDWARE).hide();
                $(CLASS_2NODE).hide();
                $(CLASS_IPV6).hide();
                $(CLASS_IPV4_DHCP).hide();
                $(CLASS_IPV6_DHCP).hide();
                
                getApplianceData();
                getDateTime();
                getNTPservers();
                getLocale();
                
                getConfiguredNICs();
                
                backupStatusView.init();
                // resize the panels
                $(PANELS).hpStackedPanels('reset'); 
                commonDisplayView.manageDisplayInOverviewDropdown();
            };
            
            function getConfiguredNICs(){
                networkPresenter.getConfiguredNICs({
                    success: function(multiNicDTO) {
                        $.each( multiNicDTO.applianceNetworks, function( key, value ) {
                            var interfaceTypeVal = '';
                            if(value.device == 'eth0')
                            {
                             base.setApplianceMoreView(true);
                             networkInterfaceTableView.setPrimaryNetworkObj(this);
                             base.setPrimaryNetworkObj(this);
                             interfaceTypeVal = 'Primary';
                             base.setFormLayout(this);
                             base.fillFields(this);
                             }
                      });
                   },
                   error: base.onError
                });
               }

            this.resume = function() {
                registerEvents();

                base.setApplianceMoreView(true);
                base.resume({
                   success: function(){
                       
                   },error: function(){
                       
                   }
               });
                if (networkPresenter.iPv6Disabled()) {
                   $(CLASS_IPV6_DISABLE).remove();
                } 
                $(CLASS_VALUE).addClass('hp-unavailable').empty();
                $(CLASS_1NODE).show();
                $(CLASS_HARDWARE).hide();
                $(CLASS_2NODE).hide();
                $(CLASS_IPV6).hide();
                $(CLASS_IPV4_DHCP).hide();
                $(CLASS_IPV6_DHCP).hide();                
                
                getConfiguredNICs();
                getApplianceData();
                getDateTime();
                getNTPservers();
                getLocale();
                backupStatusView.resume();
                $(PANELS).hpStackedPanels('resume');
                commonDisplayView.manageDisplayInOverviewDropdown();
            };
            this.pause=function(){
                removeEvents();
                manageClock(false);
                $(PANELS).hpStackedPanels('pause');
            };

        }
        return new ApplianceMoreView();
    }());

    return ApplianceMoreView;
});
