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

define(['hp/core/Notifications',
        'hp/model/TaskFollower',
        'hp/core/Localizer',
        'hp/services/Log',
        'hp/model/Session',
        'fs/view/settings/backup/BackupTaskNotificationFormatter',
        'fs/presenter/settings/BackupActionPresenter',
        'fs/view/settings/backup/BackupStatusView'],
function(notifications, taskFollower, localizer, log,
    session, BackupTaskNotificationFormatter, presenter, statusView) { "use strict";

    var BackupActionView = (function() {
    
        /**
         * Constants
         */
         var SETTINGS_SHOW_SECTION = '#hp-settings-show';
         var NOTIFY_STATUS_ERROR = 'error';
         var RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND';
         var UPLOADED = 'UPLOADED';
         var TASK_STATE_COMPLETED = 'Completed';
         var ADD_NOTIFICATION = 'addNotification';

        /**
         * @constructor
         */
        function BackupActionView() {
        
            var taskFormatter = new BackupTaskNotificationFormatter();
            var downloadLastBackup;    // forward declaration
            
            function addErrorNotification(summary, error, resolution) {
                var notification = {
                    summary    : summary + " " + error,
                    status     : NOTIFY_STATUS_ERROR,
                    details    : " ",
                    resolution : resolution
                };
                
                $(SETTINGS_SHOW_SECTION).trigger(ADD_NOTIFICATION, notification);
            }
            
            function handlerErrorFromPresenter(message, errorInfo) {
                addErrorNotification(message, errorInfo.message, errorInfo.resolution);
            }
            
            function handleError(summaryKey, errorKey, resolutionKey) {
               addErrorNotification(
                   localizer.getString(summaryKey),
                   localizer.getString(errorKey),
                   localizer.getString(resolutionKey)
               );
            }
            
            function reportUnableToStartBackup(errorInfo) {
                handlerErrorFromPresenter(
                    localizer.getString(
                        'fs.settings.backup.unableToStartBackup'
                    ), 
                    errorInfo
                );
            }
            
            function reportBackupInProgress() {
                handleError(
                    'fs.settings.backup.unableToDownloadBackup',
                    'fs.settings.backup.backupInProgress',
                    'fs.settings.backup.waitForBackupToComplete'
                ); 
            }
            
            function reportNoBackupExists() {
                handleError(
                    'fs.settings.backup.unableToDownloadBackup',
                    'fs.settings.backup.noBackup',
                    'fs.settings.backup.createBackupAndRetry'
                ); 
            }
            
            function reportUploadedBackupExists() {
                handleError(
                    'fs.settings.backup.unableToDownloadBackup',
                    'fs.settings.backup.uploadedBackup',
                    'fs.settings.backup.createBackupAndRetry'
                ); 
            }
            
            function reportGetBackupForDownloadError(errorInfo) {
                handlerErrorFromPresenter(
                    localizer.getString(
                        'fs.settings.backup.unableToDownloadBackup'
                    ), 
                    errorInfo
                );
            }
            
            function addNotification(notification) {
                $(SETTINGS_SHOW_SECTION).trigger(ADD_NOTIFICATION, notification);
            }
            
            function updateBackupStatusView() {
                statusView.update();
            }
            
            function startBackupDownload(downloadUri) {
                window.location = downloadUri;
            }
            
            function onGetBackupSuccess(backupResource) {
                if (!backupResource) {
                    reportNoBackupExists();   
                } else if (presenter.isBackupInProgress(backupResource)) {
                    reportBackupInProgress();
                } else if (presenter.isGoodBackup(backupResource)) {
                    if (backupResource.backupType === UPLOADED) {
                        reportUploadedBackupExists();
                    } else {
                        var downloadUri = presenter.getDownloadUri(backupResource);
                        startBackupDownload(downloadUri);
                    }
                } else {
                    reportNoBackupExists();
                }
            }
            
            function onGetBackupError(errorInfo) {
                if (errorInfo.errorCode === RESOURCE_NOT_FOUND) {
                    reportNoBackupExists(); 
                } else {
                    reportGetBackupForDownloadError(errorInfo);
                }
            }
            
            function onBackupStatusChanged(taskResource) {
                var notification = taskFormatter.getNotification(taskResource);
              
                if (taskFollower.isTaskFinished(taskResource)) {
                    addNotification(notification);
                    notifications.add(notification, true);
                    if (taskResource.taskState === TASK_STATE_COMPLETED) {
                        var backupUri = taskResource.associatedResourceUri;
                        var backupId = taskFormatter.getBackupId(backupUri);
                        $('.' + backupId).live('click', downloadLastBackup);
                    }
                } else  /* task not finished */ {
                    addNotification(notification);
                }
                
                updateBackupStatusView();
            };
            
            function onStartBackupError(errorInfo) {
                reportUnableToStartBackup(errorInfo);
            }
            
            downloadLastBackup = function() {
                presenter.getLastBackupForDownload(
                    {success: onGetBackupSuccess, 
                     error: onGetBackupError
                    }
                );
            };
            
            /**
             * Download the last backup 
             */
            this.downloadLastBackup = downloadLastBackup;
            
            /**
             * Start backup 
             */
            this.startBackup = function() {
                presenter.startBackup(
                    {changed: onBackupStatusChanged,
                     error: onStartBackupError 
                    }
                );
            };
            
            this.init = function() {
                presenter.init();
            };
            
            this.pause = function() {
               // nothing
            };

            this.resume = function() {
               // nothing
            };

        }

        return new BackupActionView();
    }());

    return BackupActionView;
});
