//(C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['hp/core/Notifications',
        'hp/core/Localizer',
        'fs/presenter/settings/CertificatePresenter',
        'fs/presenter/settings/AuthNPresenter',
        'fs/presenter/settings/SettingsPresenter',
        'hp/core/EventDispatcher',
        'hp/model/Session',
        'hp/lib/date',
        'lib/jquery.dateFormat'],
function(notifications, localizer, certificatePresenter,authnPresenter,settingsPresenter, dispatcher ,session) { "use strict";

    var SecurityShowView = (function() {

        var VIEW = '#fs-settings-security-panel',
            EDIT_LINK = '#cic-settings-security-edit',
            UNSET = 'hp-unset',
            COMMON_NAME = '#fs-settings-security-overview-common-name',
            VALID_UNTIL = '#fs-settings-security-overview-valid-until',
            EXPIRES_IN = '#fs-settings-security-overview-expires-in',
            ADD_NOTIFICATION = 'addNotification',
            DIRECTORIES_LIST = '#fs-settings-security-overview-directories',
            ALLOW_LOCAL_LOGIN_VALUE_CONATINER = '#cic-settings-security-authn-allow-local',
            DEFAULT_PROVIDER_VALUE_CONTAINER = '#cic-settings-security-authn-default-provider',
            SECURITY_FIRMWAREBUNDLE_OVERVIEW_LINK = '#fs-settings-security-firmwarebundle-selector-listitem';

        /**
         * @constructor View logic for the Security pane in the Settings Overview page.
         */
        function SecurityShowView() {

         // 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 ] );
           }

        // Displays an warning 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 showWarning(error) {
                $(VIEW).trigger(ADD_NOTIFICATION, [{
                    summary: error.errorMessage,
                    details: error.resolution,
                    status: 'warning'
                 }, true ] );
             }

         // Show the contents of a field, with handling of "not set".
            function setField(field, value) {
                if (value) {
                    $(field).text(value).removeClass(UNSET);
                } else {
                    $(field).html('<span class="hp-help">' + localizer.getString('core.common.notset') + '</span>');
                }
            }

            function makeLink(name, uri) {
                var link = name;
                if (session.canPerformAction("appliance", "Update")) {
                     link = '<a href="#' + uri + '">' + name + '</a>';
                }
                return link;
           }


         // Display the certificate data (called when it is received from the server).
            function showCertificateData(certObject) {
              setField(COMMON_NAME, certObject.commonName);
              var valid_until = null;
              if (certObject.validUntil) {
                  valid_until = $.format.date(Date.parseISOString(certObject.validUntil), 'yyyy-MM-dd') + "T" +
                      $.format.date(Date.parseISOString(certObject.validUntil), 'HH:mm:ss')+
                      $.format.date(Date.parseISOString(certObject.validUntil), 't');
              }
              setField(VALID_UNTIL, valid_until);
              var expires_in = certObject.expiresInDays;
              if (expires_in < 31) {
                $(EXPIRES_IN).html('<span class="hp-warning">' + localizer.getString('fs.settings.security.overview.expires_in', [ expires_in ]) +
                    '</span>').removeClass(UNSET);
                var msg = localizer.getString('fs.settings.security.overview.expires_detail_message',
                       [ valid_until, expires_in ]) + "</br></br>" + localizer.getString('fs.settings.security.overview.expires_resolution',[
                          makeLink('Create self-signed certificate', '/settings/add/appliance_certificate'),
                          makeLink('Create certificate signing request', '/settings/add/appliance_csr')] );

                var warning = {
                        errorMessage : localizer.getString('fs.settings.security.overview.expires_message', [ expires_in ]),
                        resolution : msg
                     };
                showWarning(warning);
              } else if (expires_in < 184) {
                $(EXPIRES_IN).html('<span class="hp-help">' + localizer.getString('fs.settings.security.overview.expires_in', [ expires_in ]) +
                    '</span>').removeClass(UNSET);
              }
            }

            // Retrieve the certificate data from the server.
            function getCertificateData() {
                certificatePresenter.getCertificate({
                    success: showCertificateData,
                    error: showError
                });
            }
            function getDirectoriesData(){
                $(DIRECTORIES_LIST).empty();
                var authConfigs = authnPresenter.getProviderConfigs();
                var defaultDirectory = authnPresenter.getDefaultProviderDisplayValue();
                if("local" === defaultDirectory.toLowerCase()) {
                  $(DIRECTORIES_LIST).append(localizer.getString('fs.settings.authn.local') + localizer.getString('fs.settings.authn.default_directory'));
                  $(DIRECTORIES_LIST).append("<br/>");
                } else {
                  $(DIRECTORIES_LIST).append(localizer.getString('fs.settings.authn.local'));
                  $(DIRECTORIES_LIST).append("<br/>");
                }

                for (var i=0; i<authConfigs.length; i+=1) {
                    var name = authConfigs[i].name;
                    if(name.toLowerCase() === defaultDirectory.toLowerCase()) {
                    $(DIRECTORIES_LIST).append(name + localizer.getString('fs.settings.authn.default_directory'));
                    } else {
                    $(DIRECTORIES_LIST).append(name);
                   }
                    $(DIRECTORIES_LIST).append("<br/>");
                }
            }
            //Retrieve authentication data from server
            function onGetGlobalSettingsSuccess() {
             $(ALLOW_LOCAL_LOGIN_VALUE_CONATINER).text(authnPresenter.getAllowLocalLoginDisplayValue());
             $(DEFAULT_PROVIDER_VALUE_CONTAINER).text(authnPresenter.getDefaultProviderDisplayValue());
             getDirectoriesData();
             }
            function onGetGlobalSettingsError(errorInfo) {
               var failureMessage = localizer.getString('fs.settings.authn.failed_get_global_settings');
                   dispatcher.fire('getGlobalSettingsError', {
                      "errorInfo" : errorInfo,
                      "failureMessage" : failureMessage
                  });
            }

            function getProductConfigSuccess(productConfigs){
                if (productConfigs["settings.security.firmwarebundles.show"] === "true"){
                    $(SECURITY_FIRMWAREBUNDLE_OVERVIEW_LINK).show();
                }else{
                    $(SECURITY_FIRMWAREBUNDLE_OVERVIEW_LINK).hide();
                }
            }

            function getProductConfigError(errorInfo){
                $(SECURITY_FIRMWAREBUNDLE_OVERVIEW_LINK).hide();
            }

            /*
             * Register Events with Presenter layer
             */
           function registerEvents(){
                authnPresenter.on("getGlobalSettingsError", onGetGlobalSettingsError);
                authnPresenter.on("onGetAllProvidersComplete", onGetGlobalSettingsSuccess);
                settingsPresenter.on('getProductConfigSuccess', getProductConfigSuccess);
                settingsPresenter.on('getProductConfigError', getProductConfigError);

            }
            /*
             * Un-Register Events
             */
            function removeEvents(){
                authnPresenter.off("getGlobalSettingsError", onGetGlobalSettingsError);
                authnPresenter.off("onGetAllProvidersComplete", onGetGlobalSettingsSuccess);
                settingsPresenter.off('getProductConfigSuccess', getProductConfigSuccess);
                settingsPresenter.off('getProductConfigError', getProductConfigError);

            }


            /**
             * Initialize the view by starting the data retrieval from the server.
             */
            this.init = this.resume = function() {
               if (session.canPerformAction("appliance", "Update")) {
                $(EDIT_LINK).show();
                 }else{
                     $(EDIT_LINK).hide();
                }
               getCertificateData();
               registerEvents();
               authnPresenter.loadSettingsEdit();
               settingsPresenter.getProductConfig();
               $(DIRECTORIES_LIST).empty();
           };
            this.pause=function(){
                removeEvents();
                $(DIRECTORIES_LIST).empty();
            };

        }

        return new SecurityShowView();

    }());

    return SecurityShowView;

});
