// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/presenter/settings/ApplianceUpdatePresenter',
        'hp/core/Localizer',
        'hp/core/Notifications',
        'hp/view/DialogView',
        'hp/services/Log',
        'hp/model/Session',
        'hp/view/UploaderView',
        'hp/view/FormStateView',
        'hp/core/Router',
        'jquery',
        'hp/lib/jquery.hpCollapsible', 'hp/lib/jquery.hpProgressBar', 'hp/lib/jquery.hpFileChooser', 'hp/lib/interval'],
function(presenter, localizer, notifications, DialogView, log, session, UploaderView, FormStateView, router) {"use strict";

var ApplianceUpdateAndInstallView = ( function() {

    var docType = "release";
    var time = null;
    var fileUploadStopDialog=null;

 // buttons/links in the form
    var INSTALL_BOX_VERSION = '#fs-settings-update-install-box-version',
        INSTALL_BOX_FILENAME = '#fs-settings-update-install-box-filename',
        CANCEL_UPDATE_LINK = '#fs-settings-update-install-box-cancel-update',
        UPDATE_INSTALL_BOX = '#fs-settings-update-install-box',
        RELEASE_NOTES_LINK = '#fs-settings-update-release-notes',
        RELEASE_NOTES_OVERLAY = '#fs-settings-update-releaseNotes-overlay',
        UPLOADER_BOX = "#fs-upload-viewer",
        UPLOADER_BOX_REST = '#fs-upload-viewer-rest',
        UPLOAD_PROGRESSBAR = "#fs-upload-progressbar",
        UPLOADER_BOX_FILE_NAME = '#fs-upload-viewer-filename',
        UPLOADER_TIME = '#fs-upload-timeRemaining',
        CANCEL_BUTTON = '#fs-upload-cancel',
        UPGRADE_TIME_WARNING = '#fs-settings-update-warning-upgradeTime',
        UPGRADE_CANCEL_DIALOG = '#fs-settings-upload-cancel-dialog',
        UPGRADE_CANCEL_DIALOG_BODY = '#fs-settings-upload-cancel-body',
        ACCEPT_EULA_LINK = '#fs-settings-update-install-box-eula';
    /**d
     * Constructor
     */
    function ApplianceUpdateAndInstallView() {

        function isIE8or9(){
            if($.browser.msie && ($.browser.version=="8.0" || $.browser.version=="9.0")){
                return true;
            }
            return false;
        }

        function formatError(errorInfo) {
            var failureNotificationDetails = errorInfo.message + "  " +
                (errorInfo.recommendedActions ? errorInfo.recommendedActions.join(' ') : "");
            return failureNotificationDetails;
        }

        function displayError(message) {
            notifications.add({
                summary: 'Upload',
                details: message,
                sourceName: presenter.getFileSelection().files[0].name,
                uri: 'appliance_update_' + presenter.getUploadID(),
                status: 'error'
            }, true /*flash*/);
        }

        function error(errorInfo){
            if(errorInfo) {
                var failureNotificationDetails = formatError(errorInfo);
                displayError(failureNotificationDetails);
            }
        }
        function resetProgress() {
            $(UPLOAD_PROGRESSBAR).hpProgressBar(0);
        }

        function reset() {
            resetProgress();
            $(UPDATE_INSTALL_BOX).hide();
            $(RELEASE_NOTES_OVERLAY).empty();
            $(UPGRADE_TIME_WARNING).empty();
            $(UPLOADER_BOX).hide();
            time = null;
        }

        function createSuccessContent() {
            $(UPLOADER_BOX).hide();
            $(UPDATE_INSTALL_BOX).show();
            return [$(UPDATE_INSTALL_BOX)];
        }

        function onUploadSuccess(data) {
            resetProgress();
            $(UPLOADER_BOX).hide();
            $(INSTALL_BOX_VERSION).text(data.version);

            $(INSTALL_BOX_FILENAME).text(data.fileName);
            $(CANCEL_UPDATE_LINK).off('click');
            $(CANCEL_UPDATE_LINK).on('click', function(){
                presenter.removeFile();
                router.go("/settings/show/overview", "appliance update upload success");
            });

            presenter.setFileName(data.fileName);
            presenter.setEstimatedUpgradeTime(data.estimatedUpgradeTime);
            $(RELEASE_NOTES_LINK).off('click');
            $(RELEASE_NOTES_LINK).on('click', function(){
                presenter.releaseNotes(data.fileName, docType, {
                    success : function(releaseNotesData){
                        var my_window = window.open("","_blank","scrollbars=1");//"", "mywindow1", "scrollbars=1"
                        my_window.document.write(releaseNotesData);
                    },
                    error : function(releaseNotesErrorInfo){
                        error(releaseNotesErrorInfo);
                    }
                });
            });
            $(ACCEPT_EULA_LINK).off('click');
            $(ACCEPT_EULA_LINK).on('click', function(){
                router.go("/settings/update/eula", "appliance update upload success");
            });

            presenter.setRebootRequired(data.rebootRequired);
            $(UPDATE_INSTALL_BOX).show();
            createSuccessContent();
            $(UPGRADE_TIME_WARNING).text(localizer.getString('fs.settings.appliance.update.applyWarning',
                    [data.estimatedUpgradeTime]));
            presenter.clearUpdateHandlers();
        }

        function onUploadProgress(data)
        {
            var percent = Math.round((data.data.loaded/data.data.total) * 100);
            if(presenter.getRemainingTime() || !presenter.getRemainingTime()=="0") {
                time = new Interval(presenter.getRemainingTime());
                if(time.hours =="0" && time.minutes=="0" && time.seconds=="0")
                {
                    $(UPLOADER_TIME).text(localizer.getString('fs.settings.appliance.update.uploadValidating'));
                    $(CANCEL_BUTTON).hide();
                }
                else {
                    $(UPLOADER_TIME).text(localizer.getString('fs.settings.appliance.update.uploadTime',[time.hours+"h"+time.minutes+"m"+time.seconds+"s"]));
                    $(CANCEL_BUTTON).show();
                }
                $('.hp-timestamp').hpTimestamp();
            }
            $(UPLOAD_PROGRESSBAR).hpProgressBar(percent);
        }

        function onDeleteSuccess(){
            presenter.clear();
            presenter.clearUpdateHandlers();
            removeEvents();
            router.go("/settings/show/overview", "appliance update delete success");
        }

        function onUploadCancel(errorInfo){
            error(errorInfo);
            removeUploadHandlers();
            presenter.clearUpdateHandlers();
            removeEvents();
            router.go("/settings/show/overview", "appliance upload cancel");
        }

        function onUploadError(errorInfo){
            error(errorInfo);
            removeUploadHandlers();
            presenter.clearUpdateHandlers();
            removeEvents();
            router.go("/settings/show/overview","appliance upload error");
        }

        function onDeleteError(){
            //Nothing to do other than redirecting
            presenter.clearUpdateHandlers();
            removeEvents();
            router.go("/settings/show/overview","appliance delete error");
        }

        function registerEvents() {
            presenter.on("deleteSuccess", onDeleteSuccess);
            presenter.on("deleteError", onDeleteError);
        }

        function addUploadHandlers(){
            presenter.on("uploadSuccess", onUploadSuccess);
            presenter.on("uploadError", onUploadError);
            presenter.on("uploadProgress",onUploadProgress);
            presenter.on("uploadCancel", onUploadCancel);
        }

        function removeEvents() {
            presenter.off("deleteSuccess", onDeleteSuccess);
            presenter.off("deleteError", onDeleteError);
         }

        function removeUploadHandlers(){
            presenter.off("uploadSuccess", onUploadSuccess);
            presenter.off("uploadError", onUploadError);
            presenter.off("uploadProgress",onUploadProgress);
            presenter.off("uploadCancel", onUploadCancel);
        }

        this.pause = function() {
            presenter.pause();
            removeEvents();
        };

        this.resume = function() {
            presenter.resume();
            registerEvents();
            reset();
            var selection = presenter.getFileSelection();
            $(UPLOADER_BOX_FILE_NAME).text(selection.files[0].name);
            $(UPLOADER_BOX).show();
            if(!isIE8or9()){
                $(UPLOADER_BOX_REST).show();
            }
            addUploadHandlers();
            presenter.upload(selection);
        };
    /**
     * Initialization.
     */
        this.init = function() {

            presenter.init();
            registerEvents();

            fileUploadStopDialog = $(UPGRADE_CANCEL_DIALOG).remove().show();

            reset();

            var selection = presenter.getFileSelection();

            $(CANCEL_BUTTON).off('click');
            $(CANCEL_BUTTON).on('click', function(){
                $(UPGRADE_CANCEL_DIALOG_BODY, fileUploadStopDialog).text(localizer.getString('fs.settings.appliance.update.uploadFileStop', [selection.files[0].name]));
                new DialogView({contents: fileUploadStopDialog,
                    ok: function (elem) {
                        presenter.cancelUpload();
                    }
                });
            });

            $(UPLOADER_BOX_FILE_NAME).text(selection.files[0].name);

            $(UPLOADER_BOX).show();
            if(!isIE8or9()){
                $(UPLOADER_BOX_REST).show();
            }

            addUploadHandlers();
            presenter.upload(selection);

        };
    }

    return new ApplianceUpdateAndInstallView();
}());

return ApplianceUpdateAndInstallView;
});
