/*
 *  Copyright 2014 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 button allows to search contents select some of them and reference them as given metadata of the selected content
 */
Ext.define('Ametys.plugins.contentstree.AddExistingContentToCurrentSelectionButtonController', {
	extend: "Ametys.ribbon.element.ui.ButtonController",
	
	statics: {
		/**
		 * @private
		 * The action of this controller
		 * @param {Ametys.ribbon.element.ui.ButtonController} controller The button controller
		 * @param {Boolean} state The toggle state or null
		 */
		act: function(controller, state)
		{
			var target = controller.getMatchingTargets()[0];
			
			if (target != null)
			{
				var contentId = target.getParameters().id;
				var messageType = target.getId();

				controller.act(contentId, messageType);
			}
		}
	},
	
	/**
	 * @cfg {String} source-editWorkflowActionId (required) This is the value of the edit action in the workflow of the source object. If the action is not available, the button will remain grayed.
	 */
	/**
	 * @cfg {String} source-metadata-ref (required) The metadata id to edit to add the new content or sub-content. The metadata type must fit one of those.
	 */
	/**
	 * @cfg {String} searchModelId (required) The id of search model to base search on.
	 */
	/**
	 * @cfg {String} boxIcon (required) The full path to icon (16x16 pixels) for the dialog box
	 */
	/**
	 * @cfg {String} boxTitle (required) The title of the dialog box.
	 */
	/**
	 * @cfg {String} boxHelpMessage1 (required) The message displayed at the top of the first card
	 */
	/**
	 * @cfg {String} boxHelpMessage2 (required) The message displayed at the top of the second card
	 */
	/**
	 * @cfg {String} [allowMultipleSelection=false] `true` to allow selecting multiple contents, `false` otherwise.
	 */
	/**
	 * @cfg {String} action Default to "Ametys.cms.content.tree.AddExistingContentToCurrentSelectionButtonController#act"
	 * @private
	 */
	 /**
     * @cfg {String} unavailable-workflowaction-description The description when the workflow action is not available on source object.
     */
	
	constructor: function(config)
	{
		config['action'] = config['action'] || "Ametys.plugins.contentstree.AddExistingContentToCurrentSelectionButtonController.act";
		
		this.callParent(arguments);
	},
	
    updateState: function ()
    {
        this.stopRefreshing(true);
        
        var target = this.getMatchingTargets()[0]; // multilection not supported (here assume that the number of matching targets is equals to 1)
        var availableActions = target.getParameters()['availableActions'];
        if (!Ext.Array.contains(availableActions, parseInt(this.getInitialConfig("source-editWorkflowActionId"))))
        {
            this.disable();
            this.setAdditionalDescription(this.getInitialConfig("unavailable-workflowaction-description") || this.getInitialConfig("error-description"));
        }
        else
        {
            this.enable();
            this.setAdditionalDescription();
        }
    },
    
	/**
	 * This method is called when the button is pressed
	 * @param {String} contentId The currently selected content identifier
	 * @param {String} messageType The bus message type (such as 'content')
	 */
	act: function(contentId, messageType)
	{
		Ametys.cms.uihelper.SelectContentBySearch.open({
			modelId: this.getInitialConfig("searchModelId"),
            iconCls: this.getInitialConfig("boxIconCls"),
			icon: this.getInitialConfig("boxIcon") ? Ametys.CONTEXT_PATH + this.getInitialConfig("boxIcon") : null,
			title: this.getInitialConfig("boxTitle"),
			callback: Ext.bind(this._actCb, this, [contentId, messageType], 1),
			helpmessage1: this.getInitialConfig("boxHelpMessage1"),
			helpmessage2: this.getInitialConfig("boxHelpMessage2"),
			multiple: this.getInitialConfig("allowMultipleSelection")
		});
	},
	
	/**
	 * @private
	 * The callback of #act
	 * @param {String[]} chosenContents The identifier of the contents chosen with the helper
	 * @param {String} parentContentId The identifier of the parent content
	 * @param {String} messageType The bus message type (such as 'content')
	 */
	_actCb: function(chosenContents, parentContentId, messageType)
	{
		if (chosenContents == null)
		{
			return;
		}
		
        var contentIdsToEdit = {};
        contentIdsToEdit[parentContentId] = null;
        
		Ametys.data.ServerComm.callMethod({
			role: "org.ametys.core.ui.RelationsManager",
			id: "org.ametys.cms.relations.setcontentattribute",
			methodName: "setContentAttribute",
			parameters: [
			    chosenContents,
			    contentIdsToEdit,
			    [],
			    this._getSourceAttributeRef(),
			    [this.getInitialConfig("source-editWorkflowActionId")]
			],
			callback: {
				handler: function(response, args) {
					if (response == null)
					{
						Ametys.log.ErrorDialog.display({
							title: "{{i18n PLUGINS_CONTENTSTREE_ADDEXISITNGELEMENT_NOTASSOCIATED_TITLE}}",
							text: "{{i18n PLUGINS_CONTENTSTREE_ADDEXISTINGELEMENT_NOTASSOCIATED_TEXT}}",
							category: this.self.getName()
						});
					}
					else
					{
                        var errors = response['errorMessages'];
                        if (errors && errors.length > 0)
			            {
                            var detailedMsg = "";
	                        for (var i=0; i < errors.length; i++)
                            {
	                            detailedMsg = response['errorMessages'][i] + "<br/>";
	                        }
                        
                            this.getLogger().error({
			                    message: "{{i18n PLUGINS_CONTENTSTREE_ADDEXISTINGELEMENT_NOTASSOCIATED_TEXT}}", 
			                    details: detailedMsg,
			                    defaultFocus: 0
			                });
                
			                Ametys.form.SaveHelper.SaveErrorDialog.showErrorDialog ("{{i18n PLUGINS_CONTENTSTREE_ADDEXISITNGELEMENT_NOTASSOCIATED_TITLE}}", "", detailedMsg);
                            return;
			            }

						if (response['success'] == true)
						{
							Ext.create("Ametys.message.Message", {
								type: Ametys.message.Message.MODIFIED,
								
								targets: {
									id: messageType,
									parameters: { ids: [parentContentId]}
								},
								
								parameters: {
									major: false
								}
							});
						}
					}
				}
			},
			waitMessage: true
		});
	},
	
    /**
     * @protected
     * Get the source-metadata-ref configuration.
     * @return {String} Get the source metadata ref
     */
    _getSourceAttributeRef: function()
    {
        return this.getInitialConfig("source-metadata-ref");
    }
});