//(C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['hp/core/Notifications',
        'hp/core/Localizer',
        'fs/presenter/settings/NetworkSetupPresenter',
        'fs/presenter/settings/AppliancePresenter',
        'fs/presenter/welcome/WelcomePresenter',
        'hp/model/Session',
        'hp/lib/date',
        'lib/jquery.dateFormat',
        'hp/lib/jquery.hpTimestamp'],
function(notifications,
         localizer,
         networkSetupPresenter,
         appliancePresenter,
         welcomePresenter,
         session) { "use strict";

    var ApplianceShowView = (function() {

        var VIEW = '#fs-settings-appliance-panel',
            HOSTNAME = '#fs-settings-appliance-overview-hostname',
            IPADDR = '#fs-settings-appliance-overview-ipaddr',
            IPADDR2 = '#fs-settings-appliance-overview-ipaddr2',
            VERSION = '#fs-settings-appliance-overview-version',
            MODEL = '#fs-settings-appliance-overview-model',
            DATETIME = '#fs-settings-appliance-overview-datetime',
            UPDATE = '#fs-settings-appliance-overview-update',
            ADD_NOTIFICATION = 'addNotification',
            MDASH = '&mdash;',
            UNSET = 'hp-unset',
            DEPLOYMENTIP = "#fs-settings-appliance-overview-deploymentip",
            NETWORKINTERFACESSIP = "#fs-settings-appliance-overview-networkInterfacesip",
            APPLIANCEIP = "#fs-settings-appliance-overview-applianceip";

        var CLASS_IPV6_DISABLE = '.fs-settings-ipv6-remove';
        var CLASS_SNMP_DISABLE = '.fs-settings-snmp-remove';
        var LAN_STATUS = "#fs-lan-status",
            LAN_VALUE = "#fs-lan-value",
            CPU_STATUS = "#fs-cpu-status",
            CPU_VALUE = "#fs-cpu-value",
            MEMORY_STATUS = "#fs-memory-status",
            MEMORY_VALUE = "#fs-memory-value",
            NETWORK_EDIT = "#cic-settings-network-edit";
 
        var TRAP_SNMP = '#fs-settings-appliance-overview-snmp';
        var TRAP_FORWARD = '#fs-settings-snmp-trapforwarding';

        var CLASS_NODE_STATUS = '.fs-node-status',
            CLASS_NODE_FIELD_VALUE = '.fs-node-field-value'  ;

        var authCategory = "appliance";

        /**
         * @constructor View logic for the Appliance pane in the Settings Overview page.
         */
        function ApplianceShowView() {
            var canReadTrapDest;
            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) {
                $(VIEW).trigger(ADD_NOTIFICATION, [{
                    summary: error.errorMessage,
                    details: error.resolution,
                    status: 'error'
                 }, true ] );
            }

            // Display the network data (called when it is received from the server).
            function showNetworkData(networkObject ,aliasSupportedFlag) {
                // The hostname is optional.
                if (networkObject.hostname) {
                    $(HOSTNAME).text(networkObject.hostname).removeClass(UNSET);
                } else {
                    $(HOSTNAME).text(localizer.getString('core.common.notset'));
                }
                $(IPADDR).text(networkObject.app1Ipv4Addr).removeClass(UNSET);
                if (aliasSupportedFlag && networkObject.app1Ipv4Alias != null && networkObject.app1Ipv4Alias != ''){
                    $(IPADDR2).text(networkObject.app1Ipv4Alias).removeClass(UNSET);
                }else if (aliasSupportedFlag && networkObject.app1Ipv4Alias == null ){
                    $(IPADDR2).text(localizer.getString('core.common.notset'));
                }
                if (!aliasSupportedFlag){
                    $(DEPLOYMENTIP).hide();
                }
            }

            // Display the appliance version data (called when it is received from the server).
            function showApplianceVersion(data) {
                // Format and show the version number with date.
                var date = Date.parseISOString(data.date);
                date = $.format.date(date, 'MMM d, yyyy');
                // REVISIT:  Need to internationalize the date format.
                $(VERSION).text(data.softwareVersion + ', ' + date).removeClass(UNSET);
                $(UPDATE).show();

                // Show the hardware model, or "virtual machine".
                if (data.modelNumber) {
                    $(MODEL).text(data.modelNumber).removeClass(UNSET);
                } else if (data.platformType == 'vm') {
                    $(MODEL).text(localizer.getString('fs.settings.appliance.platform.vm')).removeClass(UNSET);
                } else if (data.hardwareModel) {
                    $(MODEL).text(data.hardwareModel).removeClass(UNSET);
                } else {
                    $(MODEL).text(localizer.getString('core.common.notset'));
                }
            }
            
            function showTrapDestinations(trapDestinations)
            {
                if(canReadTrapDest)
                {
                    if(trapDestinations.members.length === 0){
                        $(TRAP_SNMP).text(localizer.getString("fs.settings.appliance.snmp.none"));                   
                    }
                    else{
                        $(TRAP_SNMP).text(trapDestinations.members.length);
                    }
                }					
            }

            // Retrieve the appliance software version and platform type from the server.
            function getApplianceData() {
                $(VERSION).html(MDASH).addClass(UNSET);
                $(MODEL).html(MDASH).addClass(UNSET);
                $(UPDATE).hide();
                appliancePresenter.getVersion({
                    success: showApplianceVersion,
                    error: showError
                });
                
                if((!(networkSetupPresenter.trapForwardingDisabled())) && canReadTrapDest){
                    appliancePresenter.getTrapDestinations({
                        success: showTrapDestinations,
                        error: showError
                    });
                }
            }
            /**
             * @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){
                        $(DATETIME).text($.format.date(d, 'MMM d, yyyy hh:mm a')+Date.tzOffsetString());
                    },
                    timeout:clockUpdateTimeout
                });
            }
            // Display the date and time data (called when it is received from the server).
            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');
                $(DATETIME).text(dateVal+Date.tzOffsetString()).removeClass(UNSET);
            }
            function registerEvents() {
                networkSetupPresenter.on("dateAndTimeChange", showDateTime);
            }
            function removeEvents() {
                networkSetupPresenter.off("dateAndTimeChange", showDateTime);
            }
            //Retrieve the date and time from the server.
            function getDateTimeData() {
                $(DATETIME).html(MDASH).addClass(UNSET);
                networkSetupPresenter.getDateTime();
            }
            // Display the date and time data (called when it is received from the server).


           function setStatus(field, minConfigMet){
                if (minConfigMet) {
                    $(field).addClass('hp-status-ok');
                } else {
                    $(field).addClass('hp-status-error');
                }
            }
            function showStatus(nodeStatus) {

                $(LAN_VALUE).html(nodeStatus.lan + " " + nodeStatus.lanUnits);
                setStatus(LAN_STATUS, welcomePresenter.isLANMinConfigMet(nodeStatus));
                $(CPU_VALUE).text(nodeStatus.cpu + " @ " + nodeStatus.cpuSpeed + " " + nodeStatus.cpuSpeedUnits);
                setStatus(CPU_STATUS, welcomePresenter.isCPUMinConfigMet(nodeStatus));
                $(MEMORY_VALUE).text(nodeStatus.memory + " " + nodeStatus.memoryUnits);
                setStatus(MEMORY_STATUS, welcomePresenter.isMemoryMinConfigMet(nodeStatus));
            }

            function handleRequestError() {
                $(CLASS_NODE_FIELD_VALUE).addClass('hp-unavailable');
                $(CLASS_NODE_STATUS).addClass('hp-status-unknown');
            }

            function getNodeStatus() {

               welcomePresenter.getNodeStatus({
                    success : function(nodeStatus) {
                        showStatus(nodeStatus);
                    },
                    error : function(errorInfo) {
                        handleRequestError();
                    }
                });
            }
            function getNICDisplay(){
                networkSetupPresenter.setNICDisplay( {
                success: function(nics,multiNICDisabled,aliasSupportedFlag,nicDisplay){
                    showNICDisplay(nics,multiNICDisabled,aliasSupportedFlag,nicDisplay);
                }
            });
            }
            
            /**
             * Display NIC ports 
             * @param nics
             * @param multiNICDisabled
             * @param aliasSupportedFlag
             * @param nicDisplay
             */
            function showNICDisplay(nics,singleNICEnabled,aliasSupportedFlag,nicDisplay){
                $(HOSTNAME).html(MDASH).addClass(UNSET);
                $(IPADDR).html(MDASH).addClass(UNSET);
                if (singleNICEnabled){
                    $(NETWORKINTERFACESSIP).hide();
                    showNetworkData(nics[0],aliasSupportedFlag);
                 }else {
                    $(APPLIANCEIP).hide();
                    $(DEPLOYMENTIP).hide();
                    $('#fs-settings-appliance-overview-networkInterfaces-ol').empty();
                    $.each(nics,function(cnt){
                        if(cnt < nicDisplay){
                            var nicPortHtml = '<li class="hp-up-port" id="nic-uplink-'+cnt+'">'+
                            '<div class="hp-condensed">'+
                            '<div id="nic-status-icon-'+cnt+'" class="hp-status">'+
                            '<span class="hp-value">warning</span>'+
                            '</div>'+
                            '</div>'+
                            '<div id ="nic-port-info-'+cnt+'"class="hp-full">'+
                            '<div class="hp-form-contents">'+
                            '<form class="hp-show-form">'+
                            '<fieldset>'+
                            '<ol id="nic-applianceIP-'+cnt+'">'+
                            '</ol>'+
                            '</fieldset>'+
                            '</form>'+
                            '</div>'+
                            '</div>'+
                            '</li>';

                            $('#fs-settings-appliance-overview-networkInterfaces-ol').append(nicPortHtml);
                            var nicStatusClass;
                            var nicDeploymentHtml;
                            var nicApplianceHtml;

                            if(nics[cnt].app1Ipv4Addr != null && nics[cnt].app1Ipv4Addr != ''){
                                if (cnt === 0 && nics[cnt].hostname) {
                                    $(HOSTNAME).text(nics[cnt].hostname).removeClass(UNSET);
                                }
                                nicStatusClass = 'hp-status-ok';

                                nicApplianceHtml = '<li class="hp-form-item">'+
                                '<label for="tour-configuration">'+localizer.getString("fs.settings.network.fields.usage")+'</label>'+
                                '<div id="nic-usage-'+cnt+'" class="hp-network-type"/>'+
                                '</li>'+
                                '<li class="hp-form-item">'+
                                '<label for="tour-state">'+localizer.getString('fs.settings.network.fields.ipaddr.short')+'</label>'+
                                '<div id="nic-address-'+cnt+'" class="hp-network-state"/>'+
                                '</li>';

                                $('#nic-applianceIP-'+cnt).append(nicApplianceHtml);
                                $('#nic-usage-'+cnt).text(nics[cnt].interfaceName).removeClass(UNSET);
                                $('#nic-address-'+cnt).text(nics[cnt].app1Ipv4Addr).removeClass(UNSET);
                                if(nics[cnt].app1Ipv4Alias != null && nics[cnt].app1Ipv4Alias != ''){
                                    nicDeploymentHtml = '<li class="hp-form-item" id="nic-deploymentIP-'+cnt+'">'+
                                    '<label for="tour-configuration">'+localizer.getString("fs.settings.network.fields.usage")+'</label>'+
                                    '<div id="nic-deployment-usage-'+cnt+'" class="hp-network-type"/>'+
                                    '</li>'+
                                    '<li class="hp-form-item">'+
                                    '<label for="tour-state">'+localizer.getString('fs.settings.network.fields.ipaddr.short')+'</label>'+
                                    '<div id="nic-deployment-address-'+cnt+'" class="hp-network-state"/>'+
                                    '</li>';
                                    $('#nic-applianceIP-'+cnt).append(nicDeploymentHtml);
                                    $('#nic-deployment-usage-'+cnt).text(localizer.getString("fs.settings.network.fields.deployment")).removeClass(UNSET);
                                    $('#nic-deployment-address-'+cnt).text(nics[cnt].app1Ipv4Alias).removeClass(UNSET);
                                }
                            }else{
                                nicStatusClass = 'hp-status-disabled';
                                $('#nic-port-info-'+cnt).hide();
                            }
                            var nicApplianceipv6Html;
                            if(nics[cnt].app1Ipv6Addr != null && nics[cnt].app1Ipv6Addr != ''){
                                nicStatusClass = 'hp-status-ok';
                                nicApplianceipv6Html = '<div id="nic-ipv6-address-'+cnt+'" class="hp-network-state"/>';
                                $('#nic-address-'+cnt).append(nicApplianceipv6Html);
                                $('#nic-ipv6-address-'+cnt).text(nics[cnt].app1Ipv6Addr).removeClass(UNSET);
                            }

                            $('#nic-status-icon-'+cnt).addClass(nicStatusClass);
                        }
                       });
            }
            }
            
            
            
            /**
             * Initialize the view by starting the data retrieval from the server.
             */
            this.init = this.resume = function() {

                canReadTrapDest = session.canPerformAction('trapforwarding','Read');

                if (networkSetupPresenter.iPv6Disabled()) {
                   $(CLASS_IPV6_DISABLE).remove();
                }
                
                if (networkSetupPresenter.trapForwardingDisabled() || !canReadTrapDest) {
                    $(CLASS_SNMP_DISABLE).remove();
                    $(TRAP_FORWARD).remove();
                }
                $(NETWORK_EDIT).toggle(session.canManageCategory(authCategory));
                getNICDisplay();
                getApplianceData();
                registerEvents();
                getDateTimeData();
                getNodeStatus();
            };
            
            this.pause = function(){
                removeEvents();
                manageClock(false);
            };
        }

        return new ApplianceShowView();

    }());

    return ApplianceShowView;

});
