/*
 *  Copyright 2016 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 class is a singleton to handle actions on user populations.
 */
Ext.define('Ametys.plugins.contentio.CollectionActions', {
    singleton: true, 
    
    /**
     * Opens the tool to create a new collection of synchronizable contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    addCollection: function(controller)
    {
        Ametys.tool.ToolsManager.openTool('uitool-edit-collection', {mode: 'add', id: '#new'});
    },
    
    /**
     * Opens the tool to edit a collection of synchronizable contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    editCollection: function(controller)
    {
        var id = controller.getMatchingTargets()[0].getParameters().id;
        Ametys.cms.contentio.SynchronizableContentsCollectionDAO.getCollection([id], this.doEdit, {scope: this});
    },
    
    /**
     * Do edit the collection
     * @param {Object} collection The collection as json returned by the server
     * @param {String} collection.id The id of the collection
     * @param {String} collection.label The label of the colelction
     */
    doEdit: function(collection)
    {
        var id = collection.id,
            label = collection.label;
            
        // Open the tool if not opened, otherwise focus it
        var tool = Ametys.tool.ToolsManager.getTool('uitool-edit-collection$' + collection.id);
        if (tool)
        {
            tool.focus();
        }
        else
        {
            Ametys.tool.ToolsManager.openTool('uitool-edit-collection', {mode: 'edit', id: id, collectionLabel: label});
        }
    },
    
    /**
     * Removes the collection of synchronizable contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    removeCollection: function(controller)
    {
        var messageTargets = controller.getMatchingTargets();
        if (messageTargets.length > 0)
        {
            var id = messageTargets[0].getParameters().id;
            Ametys.Msg.confirm("{{i18n PLUGINS_CONTENTIO_COLLECTION_REMOVE_CONFIRM_TITLE}}",
                    "{{i18n PLUGINS_CONTENTIO_COLLECTION_REMOVE_CONFIRM_MSG}}",
                    Ext.bind(this._doRemove, this, [id], 1),
                    this
            );
        }
    },
    
    /**
     * @private
     * Calls the remove server method
     * @param {String} btn The pressed button. Can only be 'yes'/'no'
     * @param {String} id The id of the population to remove
     */
    _doRemove: function(btn, id)
    {
        if (btn == 'yes')
        {
            Ametys.cms.contentio.SynchronizableContentsCollectionDAO.removeCollection([id]);
        }
    },
    
    /**
     * Save a created/edited collection of synchronizable contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    unsave: function(controller)
    {
    	var tool = Ametys.tool.ToolsManager.getFocusedTool();
    	
    	if (!tool.isDirty())
    	{
    		tool.close();
    		return;
    	}
    	
    	Ametys.Msg.confirm("{{i18n PLUGINS_CONTENTIO_COLLECTION_UNSAVE_LABEL}}", 
				"{{i18n PLUGINS_CONTENTIO_COLLECTION_UNSAVE_CONFIRM}}", 
				function (answer) {
		    		if (answer =='yes')
		    		{
		    			tool.close();
		    		}
    			},
				this
		);
    },
    
    /**
     * Save a created/edited collection of synchronizable contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    saveAndQuit: function(controller)
    {
        this._startSave(controller, true);
    },
    
    /**
     * Action function to save the collection modifications
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     * @param quit true to quit edition form after saving modifications
     * @private
     */
    _startSave: function (controller, quit)
    {
        var form = Ametys.form.SaveHelper.getForm(controller.getMatchingTargets());
        if (form != null)
        {
            // Validate form
            var invalidFields = Ext.Array.merge(form.getInvalidFields(), form.getInvalidRepeaters());
            if (invalidFields.length > 0)
            {
                Ametys.Msg.show({
                       title: "{{i18n plugin.cms:PLUGINS_CMS_SAVE_ACTION_SAVE}}",
                       msg: "{{i18n plugin.cms:PLUGINS_CMS_SAVE_ACTION_INVALIDFIELDS}}" + Ametys.form.SaveHelper.getInvalidFieldsAsReadableList(invalidFields),
                       buttons: Ext.Msg.OK,
                       icon: Ext.MessageBox.ERROR
                });
                return;
            }
            
            var target = controller.getMatchingTargets()[0];
            var collectionId = target.getParameters().id;
            var tool = Ametys.tool.ToolsManager.getTool('uitool-edit-collection$' + collectionId);
            
            var values = form.getJsonValues();
            
            var cb = quit ? function(response, args) {
                if (response && !response.error && args.tool)
                {
                    args.tool.close();
                }
            } : Ext.emptyFn;
            
            if (tool.getMode() == 'add')
            {
                Ametys.cms.contentio.SynchronizableContentsCollectionDAO.addCollection([values], cb, {scope: this, arguments: {tool: tool}});
            }
            else
            {
                Ametys.cms.contentio.SynchronizableContentsCollectionDAO.editCollection([collectionId, values], cb, {scope: this, arguments: {tool: tool}});
            }
        }
    },
    
    /**
     * @private
     * Callback function called after the 'Ok' action is processed. Close the dialog box if no error.
     * @param {Object} response The server response
     */
    _validateCb: function(response)
    {
        if (response && !response.error)
        {
            this._box.close();
        }
    }
});