/*
 *  Copyright 2015 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 create a Orgunit and reference-it or create it as sub-content of the selected content (on a given metadata)
 * If the current selection is not a orgunit, the created Orgunit will be add to the root orgunit
 */
Ext.define('Ametys.plugins.odf.orgunit.AddOrgUnitToCurrentSelectionButtonController', {
	extend: "Ametys.plugins.contentstree.AddContentToCurrentSelectionButtonController",
	
	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 targets = Ametys.message.MessageBus.getCurrentSelectionMessage().getTargets();
			var target = Ametys.message.MessageTargetHelper.findTarget(targets, function(target) {
				return target.getId() == "content" && Ext.Array.contains(target.getParameters().types, "org.ametys.plugins.odf.Content.orgunit");
			});
			
			var messageType = "content";
			if (target != null)
			{
				var contentId = target.getParameters().id;
				this._getRootOrgUnitIdCb(contentId, controller, messageType);
			}
			else
			{
				// If no orgunit is selected, we want the root orgunit to be the parent
				controller.serverCall("getRootOrgUnitId", [], Ext.bind(this._getRootOrgUnitIdCb, this, [controller, messageType], 1));
			}
		},
		
        /**
         * @private
         * Callback from #act method
         * @param {String} contentId The content identifier
         * @param {Ametys.ribbon.element.ui.ButtonController} controller The button controller acting
         * @param {String} messageType The message type such as "content"
         */
		_getRootOrgUnitIdCb: function(contentId, controller, messageType)
		{
			controller.serverCall("getModelItemType", [contentId, controller._getSourceAttributeRef()], Ext.bind(controller.act, controller, [contentId, messageType], true), null, true);
		}
	},
	
	constructor: function(config)
	{
		config['action'] = config['action'] || "Ametys.plugins.odf.orgunit.AddOrgUnitToCurrentSelectionButtonController.act"
		
		this.callParent(arguments);
	}
});