/*
 *  Copyright 2015 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * This tool display maintenance tasks status
 */
Ext.define('Ametys.repository.maintenance.MaintenanceTaskTool', 
    {
        extend: "Ametys.plugins.coreui.log.ServerLogTool",
        
        constructor: function(config)
        {
            this.callParent(arguments);
            
            // The task that will be handled by the Ext.TaskManager
            this._taskInfoTask = {
                run: this._getTaskInfo,
                scope: this,
                interval: 1000
            };
            
            this._isTaskRunning = false;
        },

        setParams: function(params)
        {
            params.category = params.category || ["org.ametys.workspaces.repository.maintenance"]
            
            this.callParent(arguments);
            
            this._taskName = params.taskName || null;
            this._setToolTitle(this._taskName);
            
            // taskinfotask must be started here.
            // store must be emptied if needed.
            var progressBar = this.grid.down("progressbar");
            if (progressBar)
            {
                progressBar.updateProgress(0, '', false); 
            }
            
            // launch task
            this._isTaskRunning = true;
            Ext.TaskManager.start(this._taskInfoTask);
        },
        
        getDockedItems: function()
        {
            return [{
                xtype: 'progressbar'
            }];
        },
        
        _setPauseDecorator: function()
        {
            // Ignore parent behavior
        },
        
        _unsetPauseDecorator: function()
        {
            // Ignore parent behavior
        },
        
        /**
         * @private
         * Change the tool title depending onn the task in progress
         * @param {String} taskName The task in progress 
         */
        _setToolTitle: function(taskName)
        {
            if (taskName == "REMOVE_UNUSED_HISTORY")
            {
                this.setTitle("{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_TOOL_TITLE_REMOVE_UNUSED_HISTORY}}");
            }
            else if (taskName == "DATA_STORE_GARBAGE_COLLECTOR")
            {
                this.setTitle("{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_TOOL_TITLE_DATA_STORE_GARBAGE_COLLECTOR}}");
            }
            else if (taskName == "REINDEXING")
            {
                this.setTitle("{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_TOOL_TITLE_REINDEXING}}");
            }
            else if (taskName == "CONSISTENCY_CHECK")
            {
                this.setTitle("{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_TOOL_TITLE_CONSISTENCY_CHECK}}");
            }
            else
            {
                this.setTitle("{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_TOOL_TITLE}}");
            }
        },
        
        /**
         * Close the tool. Just call Ametys.tool.ToolsManager#removeTool
         * @param {boolean} [manual=false] True is the close method was call by the contributor. Should be considered as false when called with no arguments
         */
        close: function(manual)
        {
            Ext.TaskManager.stop(this._taskInfoTask);
            
            this.callParent(arguments);
        },
        
        /**
         * @private
         * Ask server for informations on the running task. Callback to #_getTaskInfoCb
         */
        _getTaskInfo: function()
        {
            if (!this._isTaskRunning)
            {
                return;
            }

            Ametys.data.ServerComm.callMethod({
                role: "org.ametys.workspaces.repository.maintenance.MaintenanceTaskComponent",
                methodName: "getInformation",
                parameters: [this._taskName],
                callback: {
                    scope: this,
                    handler: this._getTaskInfoCb
                },
                errorMessage: {
                    msg: "{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_GET_TASK_INFO_ERROR_LOG}}",
                    category: 'Ametys.repository.maintenance.MaintenanceActions'
                },
                waitMessage: false
            });
        },

        /**
         * Callback for the get information on the current task
         * @param {Object} response the response from the server
         * @param {Boolean} response.isRunning Is the task still running
         * @param {Boolean} response.repositoryState Is the repository running
         * @param {Object} response.progress the current progress of the task
         */
        _getTaskInfoCb: function(response)
        {
            if (!response.isRunning)
            {
                this._isTaskRunning = false;
                Ext.TaskManager.stop(this._taskInfoTask);
                
                // Stop the autorefresh of the log list
                this.pauseUpdates(true);
                // force a refresh after 500ms to get the last log
                setTimeout(Ext.bind(this.showOutOfDate, this), 500);
            }
            
            // Update progress bar
            var progress = response.progress;
            if (progress != null)
            {
                var progressBar = this.grid.down("progressbar");
                if (progressBar)
                {
                    var progressLabel = "{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_PROGRESS_BAR_LABEL_PRE}}" + Math.round(progress.progression) + "{{i18n PLUGINS_REPOSITORYAPP_MAINTENANCE_PROGRESS_BAR_LABEL_POST}}";
                    // do not animate if displaying the last report, otherwise it gives the impression that a task has been executed
                    // when the tool is opened.
                    var animate = this._taskName != null; 
                    progressBar.updateProgress((progress.progression / 100), progressLabel, animate);
                }
            }
            
            var taskName = response.taskName || response.lastTaskName || '';
            if (this._taskName != taskName)
            {
                this._taskName != taskName; 
                this._setToolTitle(taskName);
            }
        },
        
        getColumns: function ()
        {
            var columns = this.callParent(arguments);
            
            // Modify default ServerLog config to hide the requestURI column.
            Ext.Array.each(columns, function (value) {
                if (value.dataIndex && value.dataIndex == "requestURI")
                {
                    value.hidden = true;
                }
            });
            
            return columns;
        }
    }
);