/*
 *  Copyright 2021 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.
 */
 
 /**
 * CRUD actions on form entries
 * @private
 */
Ext.define('Ametys.plugins.forms.actions.FormEntriesActions', {
	singleton: true,
	
	/**
 	 * Remove a given entry.
 	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
 	 */
 	deleteEntry: function(controller)
 	{
 		var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_ENTRY);
 		if (target == null)
        {
            return;
        }
        
 		Ametys.Msg.confirm("{{i18n PLUGINS_FORMS_DELETE_ENTRY_LABEL}}",
			"{{i18n PLUGINS_FORMS_DELETE_ENTRY_CONFIRM}}",
			Ext.bind(this._doRemove, this, [target], 1),
			this
 		);
 	},
 	
 	/**
 	 * @private
 	 * The action to perform when the user clicks on a button from the removing message box.
 	 * @param {String} btn The pressed button. Can only be 'yes'/'no'
 	 * @param {Object} target The entry target to remove.
 	 */
 	_doRemove: function(btn, target)
 	{
	 	if (btn == 'yes')
	    {
            var entryId = target.getParameters().id;
        	Ametys.plugins.forms.dao.FormEntryDAO.deleteEntry([entryId, target]);
	    }
 	},
    
    /**
     * Exports entries to XLS for a given form.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    exportXls: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        
        var params = {};
        var schedulable = "org.ametys.plugins.forms.schedulable.ExportXlsSchedulable";
        params[schedulable + "$formId"] = target.getParameters().id;
        
        var appParams = Ametys.getAppParameters();
        for (var key in appParams)
        {
            params[schedulable + "$" + key] = appParams[key];
        }
        
        controller.serverCall(
            "add",
            ["{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_LABEL}}", "{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_DESC}}", "NOW", controller.cron, schedulable, params],
            Ext.bind(this._exportXlsCB, this),
            {
                scope: this,
                arguments: {
                    taskLabel: "{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_LABEL}}",
                    formTitle: target.getParameters().title
                },
                errorMessage: true
            }
        );
    },
    
    /**
     * Callback after launching the export. Checking the schedulable progress
     * @param {Object} response The response
     * @param {Object} args The arguments with task label and form title
     * @private
     */
    _exportXlsCB: function(response, args)
    {
        if (!response.error)
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_LAUNCH_TITLE}}",
                msg: Ext.String.format("{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_LAUNCH_MSG}}", args.formTitle),
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.INFO
            });
            
            this._checkTaskState(response.id, args)
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_LAUNCH_TITLE}}",
                msg: Ext.String.format("{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_LAUNCH_ERROR}}", args.formTitle),
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    },
    
    /**
     * Check task state
     * @param {String} taskId The task identifier
     * @param {Object} args The arguments as task label or form title
     * @private
     */
    _checkTaskState: function(taskId, args)
    {
        Ametys.plugins.core.schedule.Scheduler.getTasksInformation(
            [[taskId]], 
            this._checkTaskStateCb, 
            {
                errorMessage: Ext.String.format("{{i18n plugin.core-ui:PLUGINS_CORE_UI_TASKS_ADD_TASK_BUTTON_CONTROLLER_CHECK_STATE_ERROR}}", args.taskLabel),
                scope: this, 
                arguments: args
            }
        );
    },
    
    /**
     * Callback after checking task state
     * @param {Object} response The response
     * @param {Object} args The arguments as task label or form title
     * @private
     */
    _checkTaskStateCb: function(response, args)
    {
        if (response.length > 0)
        {
            var task = response[0];
            if (task.getState() == "running")
            {
                Ext.defer(this._checkTaskState, 1000, this, [task.getId(), args]);
            }
            else if (task.getState() == "success")
            {
               Ametys.notify({
                    type: 'info',
                    title: args.taskLabel,
                    description: Ext.String.format("{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_ENDED_SUCCESS}}", args.formTitle)
                });
            }
            else if (task.getState() == "failure")
            {
               Ametys.notify({
                    type: 'error',
                    title: args.taskLabel,
                    description: Ext.String.format("{{i18n PLUGINS_FORMS_SCHEDULABLE_EXPORT_XLS_ENDED_FAILURE}}", args.formTitle)
                });
            }
        }
    },
    
    /**
     * Exports to XLS a summary of given form entries.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    summaryExportXls: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        
        var args = {
            'id': target.getParameters().id
        };
        Ametys.openWindow(Ametys.getPluginDirectPrefix('forms') + '/forms/summary/entries.xls', args);
    },
});