/*
 *  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 forms
 * @private
 */

Ext.define('Ametys.plugins.forms.actions.FormsActions', {
    singleton: true,
    
    /**
     * Opens the preview tool for a given form.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    preview: function(controller)
    {
        var target = controller.getMatchingTargets()[0],
            subtarget = target.getSubtargets()[0],
            subsubtarget,
            id = target.getParameters().id,
            pageId,
            questionId;
            
        if (subtarget)
        {
            pageId = subtarget.getParameters().id;
            subsubtarget = subtarget.getSubtargets()[0];
        }
        if (subsubtarget)
        {
            questionId = subsubtarget.getParameters().id;
        }
        
        var params = {
            id: id,
            pageId: pageId,
            questionId: questionId
        };
        
        Ametys.tool.ToolsManager.openTool('uitool-form-preview', params);
    },
    
    /**
     * Set the workflow of the form
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    setWorkflow: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        if (!target)
        {
            return;
        }
        
        var targetParameters = target.getParameters();
        var formId = targetParameters.id;
        var oldWorkflowName = targetParameters.workflowName;
        var newWorkflowName = controller.config.workflowName;
        if (oldWorkflowName != newWorkflowName)
        {
            Ametys.plugins.forms.dao.FormDAO.setWorkflow([formId, newWorkflowName]);
        }
    },
    
    /** 
     * Add a new page to form 
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    addPage : function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        if (!target)
        {
            return;
        }
        var targetParameters = target.getParameters(),
            parentId = targetParameters.id;
        Ametys.plugins.forms.dao.FormPageDAO.createPage([parentId, "{{i18n PLUGINS_FORMS_CREATE_PAGE_DEFAULT_NAME}}"]);
    },
    
    /** 
     * Rename the selected page 
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    renamePage : function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_PAGE);
        if (!target)
        {
            return;
        }
        
        var targetParameters = target.getParameters(),
            id = targetParameters.id,
            currentName = targetParameters.title;
        function _doRename(newName)
        {
            if (currentName != newName)
            {
                Ametys.plugins.forms.dao.FormPageDAO.renamePage([id, newName]);
            }
        }
        
        if (id == 'root')
        {
            return;
        }
        
        Ametys.Msg.prompt(
            "{{i18n PLUGINS_FORMS_RENAME_PAGE_PROMPT_TITLE}}",
            "{{i18n PLUGINS_FORMS_RENAME_PAGE_PROMPT_FIELD_NAME}}",
            function(btn, text) {
                if (btn == 'ok')
                {
                    _doRename(text);
                }
            },
            this,
            false,
            currentName
        );
    },
    
    /**
     * Remove a given page.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    removePage: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_PAGE);
        
        Ametys.Msg.confirm("{{i18n PLUGINS_FORMS_DELETE_PAGE_LABEL}}",
                "{{i18n PLUGINS_FORMS_DELETE_PAGE_CONFIRM}}",
                Ext.bind(this._doRemove, this, [target], 1),
                this
        );
    },
    
    /**
     * Copies a given page.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    copyPage: function(controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            // keep title too for the button's tooltip
            Ametys.clipboard.Clipboard.setData (Ametys.message.MessageTarget.FORM_PAGE, {id: targets[0].getParameters().id, title: targets[0].getParameters().title});
        }
    },
    
    /**
     * Pastes a given page.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    pastePage: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        var clipboardData = Ametys.clipboard.Clipboard.getData();
        if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.FORM_PAGE)
        {
            var formId = target.getParameters().id;
            var pageId = clipboardData[0].id;
            Ametys.plugins.forms.dao.FormPageDAO.copyPage([formId, pageId]);
        }
    },
    
    /**
     * Creates a new question of type input text.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    createQuestion: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_PAGE);
        var questionType = controller["type-id"];
        var pageId = target.getParameters().id;
        Ametys.plugins.forms.dao.FormQuestionDAO.createQuestion([pageId, questionType]);
    },
    
    /**
     * Edits a given question.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    editQuestion: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        
        Ametys.plugins.forms.helper.QuestionEditDialogHelper.open({
            questionType: target.getParameters().questionType,
            formId: target.getParameters().formId,
            id: target.getParameters().id,
            dialogTitle: target.getParameters().typeLabel,
            iconGlyph: target.getParameters().iconGlyph,
            hasRule: target.getParameters().hasRule
        });
    },
    
    /**
     * Removes a given question.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    removeQuestion: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        var confirmMsg = (target.getParameters().hasRule) ? "{{i18n PLUGINS_FORMS_DELETE_QUESTION_HAS_RULE}}" : "";
        confirmMsg += "{{i18n PLUGINS_FORMS_DELETE_QUESTION_CONFIRM}}";
        
        Ametys.Msg.confirm("{{i18n PLUGINS_FORMS_DELETE_QUESTION_LABEL}}",
                confirmMsg,
                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 {Ametys.message.MessageTarget} target The target to remove.
     */
    _doRemove: function(btn, target)
    {
        if (btn == 'yes')
        {
            if (target == null)
            {
                return;
            }
            if(target.getId() == "form-page")
            {
                Ametys.plugins.forms.dao.FormPageDAO.deletePage([target.getParameters().id, target]);
            }
            else if (target.getId() == "form-question")
            {
                Ametys.plugins.forms.dao.FormQuestionDAO.deleteQuestion([target.getParameters().id, target]);
            }
        }
    },
    
    /**
     * Copies a given question.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    copyQuestion: function(controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            // keep title too for the button's tooltip
            Ametys.clipboard.Clipboard.setData (Ametys.message.MessageTarget.FORM_QUESTION, {id: targets[0].getParameters().id, title: targets[0].getParameters().title});
        }
    },
    
    /**
     * Pastes a given question.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    pasteQuestion: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_PAGE);
        var clipboardData = Ametys.clipboard.Clipboard.getData();
        if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.FORM_QUESTION)
        {
            var pageId = target.getParameters().id;
            var questionId = clipboardData[0].id;
            Ametys.plugins.forms.dao.FormQuestionDAO.copyQuestion([pageId, questionId]);
        }
    },
    
    /**
     * Sends an email inviting the granted users who did not answered yet the form to do it.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    sendInvitations: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        var formId = target.getParameters().id;
        
        Ametys.plugins.forms.helper.FormInvitationDialogHelper.open(formId);
    },
});