//(C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['fs/view/settings/restore/UploadRestoreCommonView',
        'hp/view/FormStateView',
        'hp/view/DialogView',
        'hp/core/Localizer',
        'fs/presenter/settings/RestorePresenter',
        'fs/view/settings/restore/UploadRestoreActivityView',
        'fs/view/settings/restore/ViewCustomizer',
        'fs/view/settings/restore/FsRestoreUploadViewCustomizations',
        'hp/core/Router',
        'jquery',
        'hp/lib/jquery.hpFileChooser'],
function(common, FormStateView, DialogView, localizer,
        restorePresenter, activityView,
        customizer, customizations, router) { "use strict";
    var UploadThenRestoreView = ( function() {
        var LONG_DELAY = 2000;
        
        // elements in the HTML markup in common
        var RESTORE_DIALOG = '#fs-settings-restore-dialog',
            RESTORE_FORM = "#fs-settings-restore-form",
            
            // specific to restoreAttendedDialog
            
            UPLOAD_MODE_SELECTOR = "#fs-settings-restore-backup-uploaded-file",
            STAGED_MODE_SELECTOR = "#fs-settings-restore-backup-staged-file",
            
            FILE_CHOOSER_CONTAINER = '#fs-settings-restore-file-chooser-container',
            
            UPLOAD_AND_RESTORE_BUTTON = "#fs-settings-restore-uploadAndRestore",
            UPLOAD_ONLY_BUTTON = "#fs-settings-restore-uploadOnly",
            UPLOAD_CANCEL_BUTTON = "#fs-settings-upload-cancel",
            PRIMARY_RESTORE_BUTTON = '#fs-settings-restore-restoreFromStagedBackup',
            PRIMARY_RESTORE_BUTTON_REDIRECT = '#fs-settings-restore-restoreFromNoStagedBackup',
            PRIMARY_CANCEL_BUTTON = '#fs-settings-restore-cancel',
            
            FLYOUT_CONFIRMATION_CHECKBOX = "#fs-restore-confirmation-checkbox",
            FLYOUT_RESTORE_BUTTON = '#fs-settings-restore-confirm-restoreFromBackup',
            FLYOUT_CANCEL_BUTTON = '#fs-settings-restore-confirm-cancel',
            IMPLICATIONS_UNDERSTOOD_REQUIRED = "#fs-restore-restoreFromBackupConfirmationRequired",
            
            STOP_UPLOAD_BUTTON = '#fs-settings-restore-stopUpload',
            CLOSE_UPLOAD_BUTTON = '#fs-settings-restore-closeUpload';
        
        var CONFIRMATION_ERROR_HIDDEN_CLASS = "hp-element-hidden";
        
        var flyoutConfirmedAction = false;
        
        /**
         * Constructor
         */
        function UploadThenRestoreView() {
            
            var formStateView = new FormStateView();
            var restoreDialog =  new DialogView();
            
////////////////////////////////////////////////////////////////////////////////
/// All ordered beyond this point to make SONAR happy                        ///
////////////////////////////////////////////////////////////////////////////////
            
            var showElement = common.showElement;
            var hideElement = common.hideElement;
            
            function getImplicationsUnderstood () {
                return $(FLYOUT_CONFIRMATION_CHECKBOX)[0].checked;
            }
            
            function setImplicationsUnderstood (trueOrFalse) {
                $(FLYOUT_CONFIRMATION_CHECKBOX)[0].checked = trueOrFalse;
            }
            
            function showImplicationsUnderstoodRequired () {
                $(IMPLICATIONS_UNDERSTOOD_REQUIRED).removeClass(CONFIRMATION_ERROR_HIDDEN_CLASS);
            }
            
            function hideImplicationsUnderstoodRequired () {
                $(IMPLICATIONS_UNDERSTOOD_REQUIRED).addClass(CONFIRMATION_ERROR_HIDDEN_CLASS);
            }
            
            function hideFlyoutConfirmation () {
                var flyout = $(RESTORE_DIALOG + ' .hp-form-confirmation');
                $(UPLOAD_MODE_SELECTOR).prop('disabled', false);
                $(STAGED_MODE_SELECTOR).prop('disabled', false);
                hideElement(flyout);
                hideImplicationsUnderstoodRequired();
            }
            
            function showFlyoutConfirmation () {
                $(FLYOUT_CONFIRMATION_CHECKBOX)[0].checked = false;
                var flyout = $(RESTORE_DIALOG + ' .hp-form-confirmation');
                $(UPLOAD_MODE_SELECTOR).prop('disabled', true);
                $(STAGED_MODE_SELECTOR).prop('disabled', true);
                showElement(flyout);
            }
            
            function showFlyup(notification) {
                formStateView.setMessage(notification);
            }
            
            function flyupNoStagedFile () {
                var msg = localizer.getString('fs.settings.restore.aFileIsRequired');
                var notification = {
                    summary    : msg,
                    status     : 'error',
                    errorMessage : msg
                };
                showFlyup (notification);
            }
            
            function flyupUploadError (errorInfo) {
                var notification = {
                    summary : errorInfo.message,
                    details : errorInfo.details,
                    status : "error"
                };
                showFlyup (notification);
            }
            
            function onValidationFailure (result) {
                $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('fs.settings.restore.uploadFileFormatWarning'));
                reset();
                restorePresenter.switchToUploadMode();
            }
            
            function performUploadAndRestore() {
                reset();
                router.returnToPrevious();
                restorePresenter.switchToUploadAndRestoreMode();
            }
            
            function performUploadOnly() {
                router.returnToPrevious();
                restorePresenter.switchToUploadOnlyMode();
            }
            
            function performRestore() {
                router.returnToPrevious();
                restorePresenter.switchToRestoreMode();
            }
            
            function error(errorInfo){
                displayError(errorInfo.message, 
                    errorInfo.recommendedActions ? errorInfo.recommendedActions.join(' ') : null);
            }
            
            function clearError() {
                formStateView.reset();
            }
            
            function clearRestoreWarning() {
                restoreDialog.clearMessage();
            }
            
            function resetFileChooser() {
                $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                restorePresenter.clearFileSelection();
            }
            
            function reset() {
                clearError();
                hideFlyoutConfirmation();
                restorePresenter.softReset();
            }
            function onSoftReset () {
                clearError();
                hideFlyoutConfirmation();
            }
            function onMediumReset () {
                $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset'); // TODO: Nice if file can be left selected at some point - Browser Issue.
            }
            function onHardReset () {
                $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
            }
            
            function onUploadError(errorInfo) {
                reset();
                restorePresenter.switchToUploadMode();
                formStateView.setMessage({
                    summary : errorInfo.message,
                    details : errorInfo.details,
                    status : "error"
                });
                flyupUploadError();
            }
            
            function onFileSelection(selection) {
                reset();
                restorePresenter.setFileSelection(selection);
                setImplicationsUnderstood(false);
            }
            
            function isIE8or9(){
                if($.browser.msie && ($.browser.version=="8.0" || $.browser.version=="9.0")){
                    return true;
                }
                return false;
            }
            
            
            function vetFileSelection () {
                var fileSize, maxBackupSize;
                var selection = restorePresenter.getFileSelection();
                
                if (!selection || !selection.files) {
                    $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('core.file.chooser.invalidSelection'));
                    return false;
                }
                
                /*
                 * The back-end makes a special effort to allow this. So we will allow the type extent to be changed.
                 *
                fileName = selection.files[0].name;  // remember to define fileName above if this check is ever restored.
                if (fileName.substring(fileName.lastIndexOf('.') + 1)!="bkp"){
                    $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('fs.settings.restore.uploadFileFormatWarning', [selection.files[0].name]));
                    return false;
                }
                */
                
                fileSize = selection.files[0].size;
                maxBackupSize = restorePresenter.getMaxBackupSize();
                if( !isIE8or9() && (fileSize > maxBackupSize)){
                    maxBackupSize = (maxBackupSize / 1000000000).toFixed(2);
                    $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError',
                            localizer.getString('fs.settings.restore.backupTooBigErrMsg')
                            + ' ' +
                            localizer.getString('fs.settings.restore.backupTooBigResolutionMsg', [maxBackupSize]));
                    return false;
                }
                return true;
            }
            
            function onUploadAndRestore() {
                if (vetFileSelection()) {
                    flyoutConfirmedAction = performUploadAndRestore;
                    showFlyoutConfirmation();
                }
            }
            
            function onUploadOnly() {
                if (vetFileSelection()) {
                    flyoutConfirmedAction = performRestore;
                    restorePresenter.startFileUpload();
                    restorePresenter.softExit();
                }
            }
            
            function onUploadCancel() {
                formStateView.reset();
                reset();
                router.returnToPrevious();
                restorePresenter.stopFileUpload();
                restorePresenter.hardExit();
            }
            
            function onStopUpload() {
                router.returnToPrevious();
                restorePresenter.stopFileUpload();
                restorePresenter.hardExit();
            }
            
            function onCloseUpload() {
                router.returnToPrevious();
                restorePresenter.softExit();
            }
            
            function onPrimaryOk() {
                formStateView.reset();
                flyoutConfirmedAction = performRestore;
                showFlyoutConfirmation();
            }
            function onPrimaryOkRedirect() {
                flyupNoStagedFile();
            }
            
            function onPrimaryCancel() {
                formStateView.reset();
                reset();
                router.returnToPrevious();
                restorePresenter.hardExit();
            }
            
            function onFlyoutOk() {
                if (getImplicationsUnderstood()) {
                    hideImplicationsUnderstoodRequired();
                    hideFlyoutConfirmation();
                    if (flyoutConfirmedAction) {
                        flyoutConfirmedAction();
                    }
                } else {
                    showImplicationsUnderstoodRequired();
                }
            }
            
            function onFlyoutCancel() {
                hideFlyoutConfirmation();
            }
            
            function switchToUploadMode () {
                reset();
                restorePresenter.switchToUploadMode();
            }
            
            function switchToStagedMode () {
                reset();
                resetFileChooser();
                restorePresenter.switchToStagedMode();
            }
            
            function performDelayedSwitchToStagedMode() {
                restoreProcess = setTimeout(switchToStagedMode, LONG_DELAY);
            }
            
            function getPresenterEventHandlers () {
                var eventHandlers = {
                    softReset: onSoftReset,
                    mediumReset: onMediumReset,
                    hardReset: onHardReset,
                    uploadSuccess: switchToStagedMode,
                    uploadError: onUploadError,
                    validationFailure: onValidationFailure
                };
                return eventHandlers;
            }
            function registerEvents() {
                common.registerEvents();
                restorePresenter.registerPresenterEventHandlers(getPresenterEventHandlers());
                
                $(UPLOAD_MODE_SELECTOR).on('click', switchToUploadMode);
                $(STAGED_MODE_SELECTOR).on('click', switchToStagedMode);
                $(UPLOAD_AND_RESTORE_BUTTON).on('click', onUploadAndRestore);
                $(UPLOAD_ONLY_BUTTON).on('click', onUploadOnly);
                $(UPLOAD_CANCEL_BUTTON).on('click', onPrimaryCancel);
                
                $(STOP_UPLOAD_BUTTON).on('click', onStopUpload);
                $(CLOSE_UPLOAD_BUTTON).on('click', onCloseUpload);
                
                $(PRIMARY_RESTORE_BUTTON).on('click', onPrimaryOk);
                $(PRIMARY_RESTORE_BUTTON_REDIRECT).on('click', onPrimaryOkRedirect);
                $(PRIMARY_CANCEL_BUTTON).on('click', onPrimaryCancel);
                $(FLYOUT_RESTORE_BUTTON).on('click', onFlyoutOk);
                $(FLYOUT_CANCEL_BUTTON).on('click', onFlyoutCancel);
            }
            
            function removeEvents() {
                restorePresenter.unregisterPresenterEventHandlers(getPresenterEventHandlers());
                common.removeEvents();
                
                $(UPLOAD_MODE_SELECTOR).off('click', switchToUploadMode);
                $(STAGED_MODE_SELECTOR).off('click', switchToStagedMode);
                $(UPLOAD_AND_RESTORE_BUTTON).off('click', onUploadAndRestore);
                $(UPLOAD_ONLY_BUTTON).off('click', onUploadOnly);
                $(UPLOAD_CANCEL_BUTTON).off('click', onPrimaryCancel);
                
                $(STOP_UPLOAD_BUTTON).off('click', onStopUpload);
                $(CLOSE_UPLOAD_BUTTON).off('click', onCloseUpload);
                
                $(PRIMARY_RESTORE_BUTTON).off('click', onPrimaryOk);
                $(PRIMARY_RESTORE_BUTTON_REDIRECT).off('click', onPrimaryOkRedirect);
                $(PRIMARY_CANCEL_BUTTON).off('click', onPrimaryCancel);
                $(FLYOUT_RESTORE_BUTTON).off('click', onFlyoutOk);
                $(FLYOUT_CANCEL_BUTTON).off('click', onFlyoutCancel);
            }
            
            // TODO: Figure out how to make obsolete and decouple the following.
            this.customizeMarkup = function (src, selector) {
                customizer.customizeMarkup(src, selector);
            };
            this.customizeBehavior = function (name, behaviors) {
                customizer.customizeBehavior(name, behaviors);
            };
            this.registerPartnerCustomizations = function (parnerCustomizations) {
                customizer.registerPartnerCustomizations(parnerCustomizations);
            };
            // TODO: Figure out how to obsolete and decouple the above.
            
            this.resume = function () {
                $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                reset();
                
                restoreDialog.resume();
                registerEvents();
                restorePresenter.determineStartingMode();
            };
            
            this.pause = function() {
                removeEvents();
                restoreDialog.pause();
            }
            
            this.init = function () {
                restoreDialog.init();
                formStateView.init({form: RESTORE_FORM});
                
                $(FILE_CHOOSER_CONTAINER).hpFileChooser({onFileSelection: onFileSelection});
                
                customizer.registerPartnerCustomizations(customizations);
                reset();
                
                restorePresenter.init();
                restorePresenter.registerPresenterEventHandlers(activityView.getActivityEventHandlers());
                
                this.resume();
            };
        }
        return new UploadThenRestoreView();
    }());
    return UploadThenRestoreView;
});
