// (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',
        'hp/view/DialogHeader',
        'hp/view/DialogNotification',
        'hp/lib/jquery.hpTimestamp',
        '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, DialogHeader, DialogNotification) {"use strict";


    var ApplianceUpdateView = ( function() {

        var checkForUpdateFlag = true;
        var docType = "release";
        var selection = {};
        var time = null;
        var fileUploadStopDialog = null;
        var fileUploadDeleteDialog = null;

        // buttons/links in the form
        var APPLY_WARNING = '#fs-settings-update-warning',
            INSTALL_BOX_VERSION = '#fs-settings-update-install-box-version',
            INSTALL_BOX_FILENAME = '#fs-settings-update-install-box-filename',
            REMOVE_FILE_LINK = '#fs-settings-update-install-box-remove',
            APPLY_USERS_LOGGED_IN_COLLAPSE = '#fs-settings-update-apply-loggedInUsers-collapse',
            APPLY_USERS_LOGGED_IN_WARNING = '#fs-settings-update-apply-users-warning',
            APPLY_USERS_LOGGED_IN_COUNT = '#fs-settings-update-apply-warning-usersCount',
            APPLY_USERS_LOGGED_IN = '#fs-settings-update-apply-warning-usersLoggedIn',
            UPDATE_INSTALL_BOX = '#fs-settings-update-install-box',
            RELEASE_NOTES_LINK = '#fs-settings-update-release-notes',
            RELEASE_NOTES_OVERLAY = '#fs-settings-update-releaseNotes-overlay',
            ERROR_MSG='#fs-settings-update-appliance-error',
            INSTALL_UPDATE_BUTTON = '#fs-settings-update-installUpdate',
            UPLOAD_INSTALL_BUTTON = '#fs-settings-update-uploadInstall',
            UPLOAD_ONLY_BUTTON = '#fs-settings-update-uploadOnly',
            UPDATE_DIALOG = '#fs-settings-update-dialog',
            UPDATE_FORM = "#fs-settings-update-form",
            CANCEL = "#fs-settings-update-cancel",
            CHECK_UPDATE = "#fs-settings-update-check-box",
            FILE_CHOOSER_CONTAINER = '#fs-update-fileupload',
            UPLOADER_BOX = "#fs-upload-viewer",
            UPLOADER_BOX_REST = "#fs-upload-viewer-rest",
            UPLOADER_BOX_IE = '#fs-upload-viewer-ie',
            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_WARNING_DETAILS = '#fs-settings-update-warning-details',
            UPGRADE_CANCEL_DIALOG = '#fs-settings-upload-cancel-dialog',
            UPGRADE_CANCEL_DIALOG_BODY = '#fs-settings-upload-cancel-body',
            UPGRADE_DELETE_DIALOG = '#fs-settings-upload-delete-dialog',
            UPGRADE_DELETE_DIALOG_BODY = '#fs-settings-upload-delete-body',
            UPGRADE_DELETE_DIALOG_HEADER = '#fs-settings-upload-delete-header',
            UPGRADE_APPLIANCE_HEALTH_WARNING = '#fs-settings-update-warning-appliance-health';

        /**
         * Constructor
         */
        function ApplianceUpdateView() {

            var updateDialog = new DialogView();
            var updateDialogHeader =  new DialogHeader();
            var updateNotification =  new DialogNotification();
            var formStateView = new FormStateView();

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

            function resetProgress() {
                $(UPLOAD_PROGRESSBAR).hpProgressBar(0);
            }

            //This function will compare the disk space of root partition of appliance and twice of file size
            //Twice is the rough estimate we are assuming for uploading the file(Upload and untar)
            function checkDiskSpace (fileSize){
                if((2*fileSize) < ((presenter.getAvailableDiskSpace())*1024*1024*1024)){
                    return true;
                }
                return false;
            }

            function onFileSelection(sel) {
                selection = sel;
                presenter.setFileSelection(selection);
                clearError();
            }

            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 clearError() {
                formStateView.reset();
            }

            function clearStagingArea(){
                $(UPLOADER_BOX).hide();
                $(UPDATE_INSTALL_BOX).hide();
                $(INSTALL_UPDATE_BUTTON).attr('disabled','true');
                $(INSTALL_UPDATE_BUTTON).hide();
                $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                $(FILE_CHOOSER_CONTAINER).show();
                $(UPLOAD_INSTALL_BUTTON).show();
                $(UPLOAD_ONLY_BUTTON).show();
                $(CANCEL).text(localizer.getString('core.details.cancel'));
                selection = null;
                updateDialog.resize();
            }

            function reset() {
                updateNotification.clearMessage();
                resetProgress();
                clearError();
                presenter.clear();
                presenter.setFileSelection();
                $(APPLY_USERS_LOGGED_IN_COUNT).empty();
                $(APPLY_USERS_LOGGED_IN).empty();
                $(APPLY_USERS_LOGGED_IN_WARNING).hide();
                $(UPDATE_INSTALL_BOX).hide();
                $(RELEASE_NOTES_OVERLAY).empty();
                $(UPGRADE_TIME_WARNING).empty();;
                $(ERROR_MSG).empty();
                $(ERROR_MSG).hide();
                $(UPLOADER_BOX).hide();
                time = null;
            }

            function showWarning(status) {
                updateNotification.clearMessage();
                if(status !== "clear"){
                    var warningBoxStatus;
                    if( status === "collapsed"){
                        warningBoxStatus=false;
                    }
                    else if ( status === "expanded")
                    {
                        warningBoxStatus=true;
                    }
                    if(presenter.getOtherUsersLoggedInList().length > 0 || presenter.getUpdateState()=="1" || presenter.hasErrorOrWarning()){
                        var estimatedUpgradeTime = presenter.getEstimatedUpgradeTime();
                        if(estimatedUpgradeTime){
                            $(UPGRADE_TIME_WARNING).text(localizer.getString('fs.settings.appliance.update.applyWarning',[estimatedUpgradeTime]));
                        }
                        else {
                            $(UPGRADE_TIME_WARNING).empty();
                        }
                        if(presenter.getOtherUsersLoggedInList().length > 0){
                            $(APPLY_USERS_LOGGED_IN_COLLAPSE).show();
                            $(APPLY_USERS_LOGGED_IN_WARNING).show();
                        }
                        updateNotification.setMessage({summary: $(APPLY_WARNING).html(),
                            status: "warning",
                            details: $(UPGRADE_WARNING_DETAILS).html()
                        }, warningBoxStatus);
                    }
                }
            }

            function calculateHealth(){
                var healthData=presenter.getConditions();
                if(healthData){
                    $(UPGRADE_APPLIANCE_HEALTH_WARNING).empty();
                    for (var i=0;i<healthData.length;i++) {
                        if( healthData[i].severity =="ERROR" || healthData[i].severity =="WARNING"){
                            presenter.setErrorOrWarning();
                            var node = $('<div/>');
                            node.text(localizer.getString("fs.settings.appliance.update.healthWarning."+healthData[i].resourceType
                                    + "_" + healthData[i].severity,[healthData[i].available]));
                            $(UPGRADE_APPLIANCE_HEALTH_WARNING).append(node);
                            $(UPGRADE_APPLIANCE_HEALTH_WARNING).append('<br>');
                        }
                    }
                }
            }

            function getOtherUsersLoggedIn() {

                $(APPLY_USERS_LOGGED_IN_WARNING).hide();

                var list = presenter.getOtherUsersLoggedInList();

                var count = list.length;
                if(count > 1){
                    $(APPLY_USERS_LOGGED_IN).empty();
                    for ( var i = 0; i < count; i++) {

                        //change this to a comma separated list
                        var node = $('<span/> ');
                        node.html(list[i]);
                        if(i==(count-1)){
                            $(APPLY_USERS_LOGGED_IN).append(localizer.getString('fs.settings.appliance.update.usersLoggedInAnd'));
                        }
                        $(APPLY_USERS_LOGGED_IN).append(node);
                        if(i<(count-2)){
                            $(APPLY_USERS_LOGGED_IN).append(",");
                        }
                    }
                    $(APPLY_USERS_LOGGED_IN_COUNT)
                    .html(localizer.getString('fs.settings.appliance.update.applyBoxUsersLoggedIn', [ count ]));
                }
                else if (count == 1) {
                    $(APPLY_USERS_LOGGED_IN_COUNT)
                    .html(localizer.getString('fs.settings.appliance.update.applyBoxOneUserLoggedIn', [ list[0] ]));
                }
            }

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

            function onUploadSuccess(data) {
                resetProgress();
                clearError();
                $(UPLOADER_BOX).hide();
                $(UPLOAD_INSTALL_BUTTON).hide();
                $(UPLOAD_ONLY_BUTTON).hide();
                $(CANCEL).text(localizer.getString('core.details.cancel'));
                $(INSTALL_BOX_VERSION).text(data.version);
                $(INSTALL_BOX_FILENAME).text(data.fileName);
                $(UPGRADE_DELETE_DIALOG_HEADER, fileUploadDeleteDialog).html(localizer.getString('fs.settings.appliance.update.uploadDelete', [data.fileName]));
                $(UPGRADE_DELETE_DIALOG_BODY, fileUploadDeleteDialog).html(localizer.getString('fs.settings.appliance.update.uploadFileDeleteWarning', [data.fileName]));

                $(REMOVE_FILE_LINK).off('click');
                $(REMOVE_FILE_LINK).on('click', function(){
                    new DialogView({contents: fileUploadDeleteDialog,
                        ok: function (elem) {
                            presenter.removeFile();
                        }
                    });

                });

                presenter.setFileName(data.fileName);
                presenter.setEstimatedUpgradeTime(data.estimatedUpgradeTime);
                $(FILE_CHOOSER_CONTAINER).hide();
                $(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);
                        }
                    });
                });

                presenter.setRebootRequired(data.rebootRequired);
                $(UPDATE_INSTALL_BOX).show();
                createSuccessContent();
                $(UPGRADE_TIME_WARNING).text(localizer.getString('fs.settings.appliance.update.applyWarning',
                        [data.estimatedUpgradeTime]));
                presenter.setUpdateState("1");
                showWarning("collapsed");
                $(INSTALL_UPDATE_BUTTON).removeAttr('disabled');
                $(INSTALL_UPDATE_BUTTON).show();
                $(INSTALL_UPDATE_BUTTON).off('click');
                $(INSTALL_UPDATE_BUTTON).on('click', function(){
                    if(presenter.getUpdateState() == 1){
                        router.go('/settings/update/eula',"appliance upload success");
                    }
                });
            }

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

            function onApplySuccess(){
                router.go('/settings/update/progress',"appliance update success");
            }

            function onApplyError(errorInfo){
                error(errorInfo);
            }

            function onPendingSuccess(data){
                calculateHealth();
                getOtherUsersLoggedIn();
                if(data) {
                    onUploadSuccess(data);
                }
                else {
                    clearStagingArea();
                    clearError();
                    showWarning("expanded");
                }
            }

            function onPendingError(errorInfo) {
                onUploadError(errorInfo);
            }

            function onDeleteSuccess(){
                presenter.clear();
                presenter.setFileSelection();
                clearError();
                clearStagingArea();
                showWarning("collapsed");
            }

            function onDeleteError(errorInfo){
                error(errorInfo);
                selection = null;
            }

            function onUpgradePendingError(errorInfo){
                if(errorInfo.errorCode != 'RESOURCE_NOT_FOUND'){
                    error(errorInfo);
                }
            }

            function onUsersLoggedInSuccess() {
                //Calling this at the time of Dialog creation
                presenter.applianceHealth();
            }

            function onUsersLoggedInError(errorInfo){
                error(errorInfo);
                presenter.applianceHealth();
            }

            function checkPending(){
                var uploading= presenter.isUploading();
                if(!uploading) {
                    presenter.isPending();
                }
                else {
                    $(UPLOAD_INSTALL_BUTTON).hide();
                    $(UPLOAD_ONLY_BUTTON).hide();
                    $(CANCEL).text(localizer.getString('core.details.close'));
                }
            }

            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();
                }
                $(UPLOADER_BOX_FILE_NAME).text(data.uploadInfo.files[0].name);
                $(UPLOAD_PROGRESSBAR).hpProgressBar(percent);
            }

            function onUploadCancel(errorInfo)
            {
                onUploadError(errorInfo);
            }

            function onBeforeSend(){
                clearError();
            }

            function onApplianceHealthSuccess(data){
                checkPending();
            }

            function onApplianceHealthError(errorInfo){
                //Nothing to do. Checking if a file is already uploaded
                checkPending();
            }

            function registerEvents() {
                presenter.on("deleteSuccess", onDeleteSuccess);
                presenter.on("deleteError", onDeleteError);
                presenter.on("upgradePendingError", onUpgradePendingError);
                presenter.on("pendingSuccess", onPendingSuccess);
                presenter.on("usersLoggedInSuccess", onUsersLoggedInSuccess);
                presenter.on("usersLoggedInError", onUsersLoggedInError);
                presenter.on("applianceHealthSuccess", onApplianceHealthSuccess);
                presenter.on("applianceHealthError", onApplianceHealthError);
            }

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

            function removeEvents() {
                presenter.off("upgradePendingError", onUpgradePendingError);
                presenter.off("pendingSuccess", onPendingSuccess);
                presenter.off("deleteSuccess", onDeleteSuccess);
                presenter.off("deleteError", onDeleteError);
                presenter.off("usersLoggedInSuccess", onUsersLoggedInSuccess);
                presenter.off("usersLoggedInError", onUsersLoggedInError);
                presenter.off("applianceHealthSuccess", onApplianceHealthSuccess);
                presenter.off("applianceHealthError", onApplianceHealthError);
            }

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

            this.pause = function() {
                removeEvents();
                presenter.pause();
                showWarning("clear");
                updateDialog.pause();
                updateDialogHeader.pause();
                updateNotification.pause();
             };

            this.resume = function() {
                presenter.resume();
                registerEvents();
                updateDialog.resume();
                updateDialogHeader.resume();
                updateNotification.resume();
                presenter.usersLoggedIn();
            };

            /**
             * Initialization.
             */
            this.init = function() {

                presenter.init();
                registerEvents();


                formStateView.init({form: UPDATE_FORM});

                updateDialog.init();
                updateDialogHeader.init(UPDATE_DIALOG + ' > header');
                updateNotification.init(UPDATE_DIALOG);

                reset();

                presenter.usersLoggedIn();

                $(FILE_CHOOSER_CONTAINER).hpFileChooser({
                    onFileSelection: onFileSelection, // required to get the selection
                    compactMode: true // optional to use compact version. Default to false
                });

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

                if(!checkForUpdateFlag){
                    $(CHECK_UPDATE).hide();
                }

                $(CANCEL).on('click', function(){
                    router.go("/settings/show/overview","appliance upload on cancel");
                });

                $(UPLOAD_ONLY_BUTTON).off('click');
                $(UPLOAD_ONLY_BUTTON).on('click', function(){
                    onBeforeSend();
                    if (!selection || !selection.files) {
                        $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                        $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('core.file.chooser.invalidSelection'));
                        return;
                    }
                    else {
                        var fileName = selection.files[0].name;
                        if (fileName.substring(fileName.lastIndexOf('.') + 1)!="bin"){
                            $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                            $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('fs.settings.appliance.update.uploadFileFormatWarning', [selection.files[0].name]));
                            selection = null;
                            return;
                        }
                        else {
                            if( !isIE8or9() && !checkDiskSpace(selection.files[0].size)){
                                $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                                $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('fs.settings.appliance.update.uploadFileDiskSpaceWarning'));
                                selection = null;
                                return;
                            }
                            else{
                                $(CANCEL_BUTTON).off('click');
                                $(CANCEL_BUTTON).on('click', function(){
                                    $(UPGRADE_CANCEL_DIALOG_BODY, fileUploadStopDialog).html(localizer.getString('fs.settings.appliance.update.uploadFileStop', [selection.files[0].name]));
                                    new DialogView({contents: fileUploadStopDialog,
                                        ok: function (elem) {
                                            presenter.cancelUpload();
                                        }
                                    });
                                });
                                $(FILE_CHOOSER_CONTAINER).hide();
                                $(UPLOAD_INSTALL_BUTTON).hide();
                                $(UPLOAD_ONLY_BUTTON).hide();
                                $(CANCEL).text(localizer.getString('core.details.close'));
                                if(isIE8or9()){
                                    $(UPLOADER_BOX_REST).hide();
                                    $(UPLOADER_BOX_IE).show();
                                }
                                else {
                                    $(UPLOADER_BOX_IE).hide();
                                    $(UPLOADER_BOX_REST).show();
                                }
                                $(UPLOADER_BOX).show();
                                $(INSTALL_UPDATE_BUTTON).show();
                                $(INSTALL_UPDATE_BUTTON).attr('disabled','true');
                                showWarning("clear");
                                addUploadHandlers();
                                presenter.upload(selection);
                            }
                    }}
                });

                $(UPLOAD_INSTALL_BUTTON).off('click');
                $(UPLOAD_INSTALL_BUTTON).on('click', function(){
                    onBeforeSend();
                    if (!selection || !selection.files) {
                        $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                        $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('core.file.chooser.invalidSelection'));
                        selection = null;
                    return;
                }
                else {
                    var fileName = selection.files[0].name;
                    if (fileName.substring(fileName.lastIndexOf('.') + 1)!="bin"){
                        $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                        $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('fs.settings.appliance.update.uploadFileFormatWarning', [selection.files[0].name]));
                        selection = null;
                        return;
                    }
                    else {
                        if( !isIE8or9() && !checkDiskSpace(selection.files[0].size)){
                            $(FILE_CHOOSER_CONTAINER).hpFileChooser('reset');
                            $(FILE_CHOOSER_CONTAINER).hpFileChooser('showError', localizer.getString('fs.settings.appliance.update.uploadFileDiskSpaceWarning'));
                            selection = null;
                            return;
                        }
                        else{
                            router.go("/appliance-update","appliance upload");
                        }
                    }}
                });

            };
        }return new ApplianceUpdateView();
    }());

    return ApplianceUpdateView;
});
