/*
 *  Copyright 2019 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.
 */
 
/**
 * Helper to create a new extraction.
 */
Ext.define('Ametys.plugins.extraction.edition.ModifyExtractionDescriptionAction', {
    singleton: true,
    
    /**
     * @private
     * @property {Ametys.ribbon.element.ui.ButtonController} _controller The controller calling the action
     */
    /**
     * @private
     * @property {String} _definitionFilePath the extraction definition file path
     */
    /**
     * @private
     * @property {String} _definitionFileName the extraction definition file name
     */
    /**
     * @private
     * @property {Object} _author the extraction definition author
     * @property {String} _author.login the author's login
     * @property {String} _author.populationId the author's population identifier
     */
    /**
     * @private
     * @property {String} _canRead true if the current user can read the extraction definition
     */
    /**
     * @private
     * @property {String} _canWrite true if the current user can write the extraction definition
     */
    /**
     * @private
     * @property {String} _canAssignRights true if the current user can edit rights of the extraction definition
     */
    
    /**
     * Modify the description of the selected extraction definition file
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the action. This controller has to use org.ametys.plugins.extraction.edition.EditExtractionClientSideElement class
     */
    act: function(controller)
    {
        this._controller = controller;
        var target = controller.getMatchingTargets()[0];
        this._definitionFilePath = target.getParameters().path;
        this._definitionFileName = target.getParameters().name;
        this._author = target.getParameters().auhtor;
        this._canRead = target.getParameters().canRead;
        this._canWrite = target.getParameters().canWrite;
        this._canDelete = target.getParameters().canDelete;
        this._canAssignRights = target.getParameters().canAssignRights;
        
        var descriptionTarget = target.getSubtarget(Ametys.message.MessageTarget.CONTENT);
        var description = descriptionTarget ? descriptionTarget.getParameters().content : undefined;
        
        Ext.create('Ametys.message.Message', {
            type: Ametys.message.Message.MODIFYING,
            targets: {
                id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE,
                parameters: {
                    path: this._definitionFilePath,
                    name: this._definitionFileName,
                    description: description,
                    author: this._author,
                    canRead: this._canRead,
                    canWrite: this._canWrite,
                    canDelete: this._canDelete,
                    canAssignRights: this._canAssignRights
                }
            }
        });
            
        if (description)
        {
            this._modifyDescription(description);
        }
        else
        {
            Ametys.plugins.cms.content.actions.CreateContentAction.act(this._controller, Ext.bind(this._addDescription, this));
        }
    },
    
    /**
     * @private
     * Add the created description to the selected extraction
     * @param {Ametys.cms.content.Content} description the description to add to the selected extraction
     */
    _addDescription: function(description)
    {
        this._controller.serverCall('addDescription', [this._definitionFilePath, description.getId()], Ext.bind(this._addDescriptionCb, this, [description], 1), { ignoreCallbackOnError: false });
    },
    
    /**
     * @private
     * Callback called when the description has been added to the extraction
     * @param {Object} response response from server.
     * @param {Ametys.cms.content.Content} description the description to add to the selected extraction
     */
    _addDescriptionCb: function(response, description)
    {
        if (response.success)
        {
            // Send the modified message for the extraction definition
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.EXTRACTION_DEFINITION_FILE,
                    parameters: {
                        path: this._definitionFilePath,
                        name: this._definitionFileName,
                        description: description,
                        author: this._author,
                        canRead: this._canRead,
                        canWrite: this._canWrite,
                        canDelete: this._canDelete,
                        canAssignRights: this._canAssignRights
                    }
                }
            });
            
            this._modifyDescription(description)
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_EXTRACTION_ADD_DESCRIPTION_ERROR_DIALOG_TITLE}}",
                msg: "{{i18n PLUGINS_EXTRACTION_ADD_DESCRIPTION_ERROR_DIALOG_MSG}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    },
    
    /**
     * @private
     * Open the Content Tool to modify the given description
     * @param {Ametys.cms.content.Content} description the description to modify
     */
    _modifyDescription: function(description)
    {
        var btnConfig = this._controller.getInitialConfig();
        var editWorkflowActionId = btnConfig['editWorkflowActionId'] ? Number(btnConfig['editWorkflowActionId']) : 2;
        var viewName = btnConfig['view-name'] || 'default-edition';
        
        // Check if edit action is available
        if (Ext.Array.contains(description.getAvailableActions(), editWorkflowActionId))
        {
            var params = {
                id: description.getId(),
                mode: 'edit',
                'edit-workflow-action': editWorkflowActionId,
                'close-after-edition' : true,
                'view-name': viewName
            }
            
            // Open the Content Tool to modify the description content
            Ametys.tool.ToolsManager.openTool('uitool-content', params);
        }
    }
    
});