/*
 *  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.
 */
 
 /**
 * Actions on form directories
 * @private
 */
Ext.define('Ametys.plugins.forms.actions.FormDirectoriesActions', {
    singleton: true,
    
    /**
     * Open and add a new form to the selected directory
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    add: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_DIRECTORY);
        if (!target)
        {
            return;
        }
        
        var targetParameters = target.getParameters(),
            parentId = targetParameters.id,
            siteName = Ametys.getAppParameter("siteName");
            
        Ametys.plugins.forms.dao.FormDAO.createForm([siteName, parentId, "{{i18n PLUGINS_FORMS_CREATE_FORM_DEFAULT_NAME}}"]);
    },
    
    /**
     * Open an edit tool for the selected form
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    openForm : function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        if (!target)
        {
            return;
        }
        var targetParameters = target.getParameters(),
            id = targetParameters.id,
            title = targetParameters.title,
            fullpath = targetParameters.fullPath;
        Ametys.tool.ToolsManager.openTool("uitool-form", {id: id, title: title, path: fullpath});
        
        var params = {
            id: id,
            pageId: null,
            questionId: null
        };
        Ametys.tool.ToolsManager.openTool('uitool-form-preview', params);
    },
    
    /**
     * Rename the selected form 
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    renameForm: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        if (!target)
        {
            return;
        }
        var targetParameters = target.getParameters(),
            id = targetParameters.id,
            currentName = targetParameters.title;
        function _doRename(newName)
        {
            if (currentName != newName)
            {
                Ametys.plugins.forms.dao.FormDAO.renameForm([id, newName]);
            }
        }
        
        if (id == 'root')
        {
            return;
        }
        
        Ametys.Msg.prompt(
            "{{i18n PLUGINS_FORMS_RENAME_DIRECTORY_PROMPT_TITLE}}",
            "{{i18n PLUGINS_FORMS_RENAME_DIRECTORY_PROMPT_FIELD_NAME}}",
            function(btn, text) {
                if (btn == 'ok')
                {
                    _doRename(text);
                }
            },
            this,
            false,
            currentName
        );
    },
    
    /**
     * Removes a given form.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    removeForm: function(controller)
    {
        var target = controller.getMatchingTargets();
        
        Ametys.Msg.confirm("{{i18n PLUGINS_FORMS_DELETE_FORM_LABEL}}",
                "{{i18n PLUGINS_FORMS_DELETE_FORM_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 {Ametys.message.MessageTarget} target The target to remove.
     */
    _doRemove: function(btn, target)
    {
        if (btn == 'yes')
        {
            if (target == null)
            {
                return;
            }
            var id = target[0].getParameters().id;
            Ametys.plugins.forms.dao.FormDAO.deleteForm([id, target]);
        }
    },
    
    /**
     * Copies a given form.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    copyForm: 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_TARGET, {id: targets[0].getParameters().id, title: targets[0].getParameters().title});
        }
    },
    
    /**
     * Pastes a given form.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
     */
    pasteForm: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_DIRECTORY);
        var clipboardData = Ametys.clipboard.Clipboard.getData();
        if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.FORM_TARGET)
        {
            var formDirectoryId = target.getParameters().id;
            var formId = clipboardData[0].id;
            Ametys.plugins.forms.dao.FormDAO.copyForm([formDirectoryId, formId]);
        }
    },
    
    showEntries : function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        if (!target)
        {
            return;
        }
        var targetParameters = target.getParameters(),
            formId = targetParameters.id,
            label = targetParameters.title;
        Ametys.tool.ToolsManager.openTool("uitool-form-entries", {id: formId, formId: formId, label: label, startSearchAtOpening: true});
    },
    
    clearEntries : function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_TARGET);
        if (!target)
        {
            return;
        }
        Ametys.Msg.confirm("{{i18n PLUGINS_FORMS_CLEAR_ENTRIES_LABEL}}",
                "{{i18n PLUGINS_FORMS_CLEAR_ENTRIES_CONFIRM}}",
                Ext.bind(this._doClear, this, [target], 1),
                this
        );
    },
    
    _doClear : function(btn, target)
    {
        if (btn == 'yes')
        {
            if (target == null)
            {
                return;
            }
            var id = target.getParameters().id;
            Ametys.plugins.forms.dao.FormEntryDAO.clearEntries([id]);
        }
    },
    
    /**
     * Creates a new forms directory under the selected one
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    createFormDirectory: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_DIRECTORY);
        if (!target)
        {
            return;
        }
        
        var targetParameters = target.getParameters(),
            parentId = targetParameters.id,
            siteName = Ametys.getAppParameter("siteName");
        Ametys.plugins.forms.dao.FormDirectoryDAO.createFormDirectory([siteName, parentId, "{{i18n PLUGINS_FORMS_CREATE_DIRECTORY_DEFAULT_NAME}}"]);
    },
    
    /**
     * Rename the selected forms directory
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    renameFormDirectory: function(controller)
    {
        var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), Ametys.message.MessageTarget.FORM_DIRECTORY);
        if (!target)
        {
            return;
        }
        
        var targetParameters = target.getParameters(),
            id = targetParameters.id,
            currentName = targetParameters.title;
        function _doRename(newName)
        {
            if (currentName != newName)
            {
                Ametys.plugins.forms.dao.FormDirectoryDAO.renameFormDirectory([id, newName]);
            }
        }
        
        if (id == 'root')
        {
            return;
        }
        
        Ametys.Msg.prompt(
            "{{i18n PLUGINS_FORMS_RENAME_DIRECTORY_PROMPT_TITLE}}",
            "{{i18n PLUGINS_FORMS_RENAME_DIRECTORY_PROMPT_FIELD_NAME}}",
            function(btn, text) {
                if (btn == 'ok')
                {
                    _doRename(text);
                }
            },
            this,
            false,
            currentName
        );
    },
    
    /**
     * Delete the selected forms directories
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    deleteFormDirectory: function(controller)
    {
        var targets = controller.getMatchingTargets();
        var ids = Ext.Array.map(targets, function(target) {
            return target.getParameters().id;
        });
        
        if (targets.length > 0)
        {
            Ametys.plugins.forms.dao.FormDirectoryDAO.mustWarnBeforeDeletion([ids], promptConfirm);
        }
        
        function promptConfirm(mustWarn)
        {
            var msg = "{{i18n PLUGINS_FORMS_DELETE_DIRECTORY_CONFIRM}}" + (mustWarn ? "{{i18n PLUGINS_FORMS_DELETE_DIRECTORY_CONFIRM_WARN}}" : "");
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_FORMS_DELETE_DIRECTORY_TITLE}}", 
                msg: msg, 
                buttons: Ext.Msg.YESNO,
                icon: mustWarn ? Ext.MessageBox.WARNING : Ext.MessageBox.QUESTION,
                fn: function(btn) {
                    if(btn == 'yes')
                    {
                        doDelete();
                    }
                },
                scope: this
            });
        }
        
        function doDelete()
        {
            Ametys.plugins.forms.dao.FormDirectoryDAO.deleteFormDirectory([ids, targets]);
        }
    }
    
});