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

define(['hp/core/Localizer',
        'fs/presenter/settings/RestorePresenter',
        'fs/presenter/settings/DateTimeSetupPresenter',
        'fs/presenter/settings/BackupStatusPresenter',
        'fs/view/settings/backup/BackupStatusView',
        'jquery',
        'hp/lib/jquery.hpFileChooser',
        'hp/lib/jquery.hpProgressBar',
        'hp/lib/jquery.hpTimestamp'],
function(localizer,  restorePresenter, dateTimeSetupPresenter, backupStatusPresenter, statusView) { "use strict";
    var UploadRestoreCommonView = ( function() {
        
        var uploadProgressBarHidden = true;
        
        // elements in the HTML markup in common
        var ALL_MODES = ".fs-all-modes",
            ALL_STEPS = ".fs-all-steps",
            UPLOAD_MODE = ".fs-upload-mode",
                SELECTING_STEP = ".fs-selecting-step",
                SELECTED_STEP = ".fs-selected-step",
                UPLOADING_STEP = ".fs-uploading-step",
                UPLOADED_STEP = ".fs-uploaded-step",
                NO_PROGRESS_STEP = ".fs-no-progress-step",
                VALIDATING_STEP = ".fs-validating-step",
            STAGED_MODE = ".fs-staged-mode",
            NO_STAGED_MODE = ".fs-no-staged-mode",
            
            INFO_BACKUP_NAME = '.fs-backup-name > label',
            INFO_BACKUP_VERSION = '.fs-backup-version > label',
            INFO_BACKUP_DATE = '.fs-backup-date > label',
            INFO_BACKUP_SIZE = '.fs-backup-size > label',
            
            UPLOAD_PROGRESS_BAR = '#fs-settings-restore-upload-progress-bar',
            UPLOAD_PROGRESS_MSG = '#fs-settings-restore-upload-progress-msg',
            
            // specific to restoreAttendedDialog
            UPLOAD_MODE_SELECTOR = "#fs-settings-restore-backup-uploaded-file",
            STAGED_MODE_SELECTOR = "#fs-settings-restore-backup-staged-file";
            
        var CLEARED_BACKUP_FILE_DATA = {
                nameVal : '',
                dateVal : '',
                sizeVal : '',
                versionVal : ''
            };
        
        var localizedStrings = {
            kiloBytes : localizer.getString('fs.settings.restore.kiloBytes'),
            megaBytes : localizer.getString('fs.settings.restore.megaBytes'),
            gigaBytes : localizer.getString('fs.settings.restore.gigaBytes'),
            uploadProgressUnknowable : localizer.getString('fs.settings.restore.uploadProgressUnknowable'),
            uploading : localizer.getString('fs.settings.restore.uploading'),
            uploaded : localizer.getString('fs.settings.restore.uploaded'),
            validating : localizer.getString('fs.settings.restore.validating'),
            validated : localizer.getString('fs.settings.restore.validated')
        };
            
        /**
         * Constructor
         */
        function UploadRestoreCommonView() {
            
            var backupFileData = CLEARED_BACKUP_FILE_DATA;
            
            function getElement (selector) {
                if( Object.prototype.toString.call(selector) == '[object String]' ) {
                    return $(selector);
                } else {
                    return selector;
                }
            }
            function showElement(selector) {
                getElement(selector).removeAttr('style');
            }
            function hideElement(selector) {
                getElement(selector).css('display', 'none');
            }

            this.getElement = getElement;
            this.showElement = showElement;
            this.hideElement = hideElement;

////////////////////////////////////////////////////////////////////////////////
/// All ordered beyond this point to make SONAR happy                        ///
////////////////////////////////////////////////////////////////////////////////
            
            function fillInBackupFileData (info) {
                var nameVal, dateVal, sizeVal, versionVal;
                var data, file;
                
                var sizeUnits = ['Bytes', // Will never render but required as a placeholder by the algorithm.
                                 localizedStrings.kiloBytes,
                                 localizedStrings.megaBytes,
                                 localizedStrings.gigaBytes];
                
                function rescaleAndSelectUnits(kilo, value, units) {
                    var vu = {};
                    var ui = 0;
                    vu.value = value;
                    vu.units = units[0];
                    while (vu.value >= kilo) {
                        ui += 1;
                        vu.value = (vu.value / kilo);
                        vu.units = units[ui];
                    }
                    vu.value = vu.value.toFixed(1).replace(".0", "");
                    return vu;
                }
                
                if (info) {
                    if (info.files && info.files[0]) {
                        file = info.files[0];
                    }
                    if (info.data) {
                        data = info.data;
                    } else {
                        data = info;
                    }
                    
                    // Look for name
                    
                    if (data.id) {
                        nameVal = data.id + '.bkp';
                    }
                    if (file && file.name) {
                        nameVal = file.name;
                    }
                    if (data.name) {
                        nameVal = data.name;
                    }
                    
                    // Look for date
                    
                    if (data.modified) {
                        dateVal = data.modified;  // also an error?
                    }
                    if (file && file.lastModifiedDate) {
                        // error dateVal = file.lastModifiedDate;
                    }
                    if (data.created) {
                        dateVal = info.created;
                    }
                    
                    
                    // look for size
                    
                    if (data.backupSize && (0 < data.backupSize)) {
                        sizeVal = data.backupSize;
                    }
                    if (file && file.size && (0 < file.size)) {
                        sizeVal = file.size;
                    }
                    
                    // Look for version
                    if (data.softwareVersion) {
                        versionVal = data.softwareVersion;
                    }
                    
                    if (nameVal) {
                        backupFileData.nameVal = nameVal;
                    }
                                       
                    if (versionVal) {
                        backupFileData.versionVal = versionVal;
                    }
                    if (sizeVal) {
                        sizeVal = rescaleAndSelectUnits(1000, sizeVal, sizeUnits); // TODO 1024 is right but clashes with UI-Core
                        backupFileData.sizeVal = localizer.getString('fs.settings.restore.sizeData', [sizeVal.value, sizeVal.units]);
                    }
                } else {
                    // Pass in null info to clear all data.
                    backupFileData = CLEARED_BACKUP_FILE_DATA;
                }
                
                $(INFO_BACKUP_NAME).text(backupFileData.nameVal);
                if (dateVal) {
                    $(INFO_BACKUP_DATE).hpTimestamp(dateVal);
                } else {
                    $(INFO_BACKUP_DATE).text(backupFileData.dateVal);
                }      
                $(INFO_BACKUP_VERSION).text(backupFileData.versionVal);
                $(INFO_BACKUP_SIZE).text(backupFileData.sizeVal);
            }
            
            this.resetProgress = function () {
                $(UPLOAD_PROGRESS_BAR).hpProgressBar(0);
            };
            
            this.hideProgress = function () {
                hideElement(NO_PROGRESS_STEP);
                uploadProgressBarHidden = true;
            };
            
            function hideEverything () {
                hideElement(ALL_MODES);
                hideElement(ALL_STEPS);
            }
            
            function showUploadAndRestoreMode (fileSelection) {
                hideElement(ALL_MODES);
                hideElement(ALL_STEPS);
                fillInBackupFileData (fileSelection);
                showElement(UPLOADING_STEP);
                showElement(STAGED_MODE);
                showElement(UPLOAD_MODE);
                hideElement(NO_PROGRESS_STEP);
            }
            
            function showUploadOnlyMode () {
                hideElement(ALL_MODES);
                hideElement(ALL_STEPS);
                showElement(UPLOAD_MODE);
            }
            
            function showUploadMode () {
                $(UPLOAD_MODE_SELECTOR).attr('checked', true);
                hideElement(ALL_MODES);
                hideElement(ALL_STEPS);
                showElement(UPLOAD_MODE);
            }
            
            function showUploadProgressNoBar () {
                hideElement(NO_PROGRESS_STEP);
            }
            
            function showUploadProgressWithBar () {
                showElement(NO_PROGRESS_STEP);
                uploadProgressBarHidden = false;
            }
            
            function completeUploadProgressBar () {
                $(UPLOAD_PROGRESS_BAR).hpProgressBar(100);
            }
            
            function updateUploadProgressNoBar (message) {
                $(UPLOAD_PROGRESS_MSG).text(message);
                showUploadProgressNoBar();
            }
            
            function updateUploadProgressBar (progress) {
                var time;
                
                showUploadProgressWithBar();
                
                var percentComplete = progress.percentComplete * (98/100);
                var remainingTime = progress.remainingTime;
                var progressMessage;
                
                if ( remainingTime || !(0===remainingTime) ) {
                    time = new Interval(remainingTime);
                    if (time.hours > 0) {
                        progressMessage = 
                            localizer.getString('fs.settings.restore.uploadHMSRemaining',
                                    [time.hours, time.minutes, time.seconds]);
                    } else {
                        progressMessage = 
                            localizer.getString('fs.settings.restore.uploadMSRemaining',
                                    [time.minutes, time.seconds]);
                    }
                    $(UPLOAD_PROGRESS_MSG).text(progressMessage);
                }
                
                if (uploadProgressBarHidden) {
                    progressMessage = localizedStrings.uploading;
                    showUploadProgressWithBar();
                }
                $(UPLOAD_PROGRESS_BAR).hpProgressBar(percentComplete);
            }
            
            function provideMessageForIE8andIE9 () {
                // IE 8/9 will not fire the progressChange event
                $(UPLOAD_PROGRESS_MSG).text(localizedStrings.uploadProgressUnknowable);
            }
            
            function showSelectingStep () {
                hideElement(ALL_STEPS);
                showElement(SELECTING_STEP);
            };
            
            function showSelectedStep (fileSelection) {
                hideElement(ALL_STEPS);
                fillInBackupFileData (fileSelection);
                showElement(SELECTED_STEP);
            };
            
            function showUploadingStep () {
                hideElement(ALL_STEPS);
                provideMessageForIE8andIE9();
                showUploadProgressNoBar();
                showElement(UPLOADING_STEP);
            };
            
            function showUploadProgress (progress) {
                showUploadProgressWithBar();
            }
            
            function showValidatedStep (fileUploaded) {
                // Per UX input 1/13/2014 - Don't show VALIDATED_STEP
                fillInBackupFileData (fileUploaded);
            }
            
            function showValidatingStep () {
                hideElement(ALL_STEPS);
                $(UPLOAD_PROGRESS_MSG).text(localizedStrings.validating);
                showElement(VALIDATING_STEP);
            }
            
            function showUploadedStep () {
                hideElement(ALL_STEPS);
                $(UPLOAD_PROGRESS_MSG).text(localizedStrings.uploaded);
                showElement(UPLOADED_STEP);
            }
            
            function showUploadSuccess (stagedBackup) {
                // Per UX input 1/13/2014 - Don't show VALIDATED_STEP
                fillInBackupFileData(stagedBackup); 
            }
            
            function showSuccessStep () {
                // Per UX input 1/17/2014 - Don't show transitional Restore screen on UploadAndRestore
            }
            
            function showStagedMode (stagedBackup) {
                hideElement(ALL_MODES);
                hideElement(ALL_STEPS);
                $(STAGED_MODE_SELECTOR).attr('checked', true);
                fillInBackupFileData(stagedBackup);
                showElement(STAGED_MODE);
            }
            
            function showNoStagedMode () {
                hideElement(ALL_MODES);
                hideElement(ALL_STEPS);
                $(STAGED_MODE_SELECTOR).attr('checked', true);
                showElement(NO_STAGED_MODE);
            }
            
            function clearBackupFileData () {
                var CLEAR_VALUE = '';
                $(INFO_BACKUP_NAME).text(CLEAR_VALUE);
                $(INFO_BACKUP_DATE).text(CLEAR_VALUE);
                $(INFO_BACKUP_VERSION).text(CLEAR_VALUE);
                $(INFO_BACKUP_SIZE).text(CLEAR_VALUE);
            }
            
            function showUploadStopped () {
            }
            
            function updateBackupStatusView() {
                statusView.update();
            }
            
            function onSoftReset () {
                updateBackupStatusView();
            }
            
            function getPresenterEventHandlers () {
                var eventHandlers = {
                    initialization: hideEverything,
                    softReset: onSoftReset,
                    uploadMode: showUploadMode,
                    stagedMode: showStagedMode,
                    noStagedMode: showNoStagedMode,
                    fileSelected: fillInBackupFileData,
                    backupStaged: fillInBackupFileData,
                    uploadAndRestoreMode: showUploadAndRestoreMode,
                    uploadOnlyMode: showUploadOnlyMode,
                    selectingStep: showSelectingStep,
                    selectedStep: showSelectedStep,
                    uploadingStep: showUploadingStep,
                    uploadProgressNoBar: updateUploadProgressNoBar,
                    uploadProgressWithBar: updateUploadProgressBar,
                    uploadSuccess: showUploadSuccess,
                    uploadStopped: showUploadStopped,
                    uploadedStep: showUploadedStep,
                    validatingStep: showValidatingStep,
                    validatedStep: showValidatedStep,
                    restoreMode: showSuccessStep
                };
                return eventHandlers;
            }
            this.registerEvents = function () {
                restorePresenter.registerPresenterEventHandlers(getPresenterEventHandlers());
            }
            
            this.removeEvents = function () {
                restorePresenter.unregisterPresenterEventHandlers(getPresenterEventHandlers());
            }
            
            this.getBackupFileData = function () {
                return backupFileData;
            };
        }
        return new UploadRestoreCommonView();
    }());
return UploadRestoreCommonView;
});


