// (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',
    'hp/core/Localizer',
    'fs/shell/InitialNetworkRoutes',
    'hp/core/EventDispatcher',
    'fs/model/settings/ProductConfig',
    'hp/lib/jquery.hpStackedPanels',    
    'jqueryUI',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpSearchCombo',
    'lib/jquery.dateFormat',
    'lib/jquery-ui-timepicker-addon',
    'hp/lib/jquery.hpTimestamp',
    'lib/jquery.validate',
    'jquery',
    'lib/jquery.dataTables',
    'hp/lib/jquery-ui-timepicker-extension'],
 function(presenter, NetworkEditViewBase, NetworkInterfaceTableView, router, urlFragment,Localizer, initialRoutes, EventDispatcher, ProductConfig) {"use strict";
    return ( function() {

        var FORM = '#cic-network-form',
            PANELS = '#cic-appliance-network-panel',
            PANEL_SELECTOR = '#cic-fsnetwork-panel-selector',
            ROUTE_PREFIX = '/settings/initial-network',
            OKBUTTON = '#cic-network-ok',
            LOGOUT_BUTTON = '#fs-settings-logout',
            SPINNER = '#cic-network-spinner',
            NOTIFY_BOX = '#cic-network-details-notify',
            NOTIFY_MSG = "#cic-network-details-notify-message-id",
            NOTIFY_DISMISS = "#hp-details-notify-dismiss_link",

            MULTI_NIC_PANEL = "#fs-fsnetwork-panel-nics",
            HOSTNAME_PANEL  = "#fs-fsnetwork-panel-hostname",
            CLASS_TIMEANDLANGUAGE = '.cic-fsnetwork-timeandlanguage',
            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',
            CURRENT_DATE_TIME_TZSTRING = '#cic-datetime-tzstring',
            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_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_DISABLED_KEY = 'timeAndLanguageOnFTSDisabled';	    
        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 timeAndLanguageOnFTSDisabled = false,
            rebootOnTimeChange = false,
            timeChangeDisabled = false;


        
        function InitialNetworkView() {

            var base = new NetworkEditViewBase();
            var networkInterfaceTableView = new NetworkInterfaceTableView(); 
            
            function setControlsDisabled(disabledFlag) {       
                 $(LOGOUT_BUTTON).toggleClass('hp-disabled', disabledFlag);
                 $(OKBUTTON).toggleClass('hp-disabled', disabledFlag);
            }
            
            /**
             * Reset the errors and notifications
             */
            function resetForm() {
                validator.resetForm();
                formStateView.reset();
            };

            /**
             * @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);
                });
            }
            
            function onSuccessRedirect(redirect) {
                base.resetForm();
                // wait for 15 seconds before redirecting
                if (redirect) {
                        setTimeout( function() {
                            base.dismissDialog();}, 15000);
                } else {
                  //wait for 10 seconds for cert to relaod
                    if (presenter.shouldReloadWindow()) {
                            setTimeout( function() {
                                base.dismissDialog();
                                if(base.hasPostValidationsOccuredForFirstTime() ){
                                    router.go('/activity', 'initial settings completed redirected to activity');
                                }else{
                                    router.go('/settings', 'initial settings completed');
                                }
                                window.location.reload();
                                }, 10000);
                    } else {
                         // wait extra 10 seconds to make sure fts is done
                        setTimeout( function() {
                                base.dismissDialog();
                                
                                if(base.hasPostValidationsOccuredForFirstTime() ){
                                    router.go('/activity', 'initial settings completed redirected to activity');
                                }else{
                                    router.go('/settings', 'initial settings completed');
                                }
                                    
                                
                        }, 15000 );
                    }
                }
            }

            /**
             * @public Handle a click of the OK button by sending a REST request
             *         to set the new configuration
             */
            function onSetInitialNetworkClick() {
                if(!$(FORM).valid()) {
                    base.displayParameterError();
                    return;
                }
                setControlsDisabled(true);
                    base.apply({
                          success: onSuccessRedirect,
                          error: function() {
                              setControlsDisabled(false);
                          }
                      });
            }

            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);
                $(PANELS).hpStackedPanels('setPanelByLocation',
                    '#' + router.location());
            }


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


            this.resume = function() {
                 setControlsDisabled(false);
                 presenter.on("selectionChange", onSelectionChange);
                 $(PANELS).hpStackedPanels('resume');
            };
            
            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]:''));
                }
            }

            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();
                          $(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 /*&& (!base.getSingleNicEnabled())*/){
                              $(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();
                          $(CURRENT_DATE_TIME).hide();
                          $(DATETIME_WARNING).hide();
                          isManualSetting = false;
                      }
                    manageClock(true);
                  });
            }

            function initializeTimeAndLocation(){
                ProductConfig.getproductConfigMembers({
                    success : function(productConfigMembers) {
                        if(productConfigMembers[PC_TIME_LOCATION_DISABLED_KEY] === 'true')
                        {
                            timeAndLanguageOnFTSDisabled = true;
                        }
                        if(productConfigMembers[PC_TIME_CHANGE_DISABLED_KEY] === 'true'){
                            timeChangeDisabled = true;
                        }
                        if(productConfigMembers[PC_REBOOT_ON_APPLIANCE_DATETIME_CHANGE] === 'true'){
                            rebootOnTimeChange = true;
                        }
                        if(timeAndLanguageOnFTSDisabled){
                            $(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'
                            });
                            presenter.getLocale();
                            $(CURRENT_DATE_TIME_TZSTRING).text(Date.tzOffsetString());
                            $(CURRENT_DATE_TIME_TZSTRING).clone().insertAfter($(CURRENT_DATE_TIME_LABEL_VALUE));
                            $(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
                    });
            }
            /**
             * @public Initialization method
             */
            this.init = function() {
                $(PANEL_SELECTOR).hide();
                $(FORM).hide();
                base.setFirstTime(true);
                $(HOSTNAME_PANEL).show();
                presenter.on("selectionChange", onSelectionChange);
                base.init(ROUTE_PREFIX, FORM, {
                    success: function(){ //pageReady callback
                        $(PANELS).hpStackedPanels({
                            panelSelector : PANEL_SELECTOR
                        });
                        router.watch('appliance network section', ROUTE_PREFIX + '.*',
                                {parent: ROUTE_PREFIX, change: changeLocation});
                        $(PANEL_SELECTOR).show();
                        $(FORM).show();
                        $(SPINNER).hide();
                        base.updateNTPFieldRules();
                    }
                });

                base.setNotifyElement($(NOTIFY_BOX));
                $(MULTI_NIC_PANEL).hide();
                $(CLASS_NICS).hide();

                var validatorOptions = {};
                base.addNicsValidatorOptions(validatorOptions);
                var validator =  $(FORM).validate(validatorOptions);
                base.setValidator(validator);


               $(LOGOUT_BUTTON).on('click', function(ev) {
               if($(LOGOUT_BUTTON).hasClass('hp-disabled') ){                 
                       return false;
                   } else {
                       base.resetForm();
                       return true;
                   }
             
                });
                $(OKBUTTON).on('click', function(ev) {
                    if ( $(OKBUTTON).hasClass('hp-disabled') ){
                        return false;
                    } else {
                        onSetInitialNetworkClick.call(this);
                        ev.preventDefault();
                   }
                });
                $(NOTIFY_BOX).hide();
                $(NOTIFY_DISMISS).click(function (evt) {
                    evt.preventDefault();
                    // TODO provide better mechanism for user to remove messages
                    $(NOTIFY_MSG).html('');
                    $(NOTIFY_BOX).slideUp('fast');
                });
                
                presenter.getConfiguredNICs({
                    success: function(multiNicDTO) {
                        $.each( multiNicDTO.applianceNetworks, function( key, value ) {
                              var interfaceTypeVal = '';
                              if(value.device == 'eth0')
                              {
                                  networkInterfaceTableView.setPrimaryNetworkObj(value);
                                  //needed this for redirection 
                                  base.setPrimaryNetworkObj(value);
                                  interfaceTypeVal = 'Primary';
                                  base.setFormLayout(this);
                                  base.fillFields(this);
                              }
                           });
                        if (multiNicDTO.serverCertificate != null) {
                            base.setServerCertificate(multiNicDTO.serverCertificate);
                        }
                    },
                    error: base.onError
                });

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

               this.addValidatorOptions = base.addNicsValidatorOptions;
            };

        }
        return new InitialNetworkView();
    }());
});
