/*
 *  Copyright 2013 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.
 */

/**
 * Singleton class to delete contents
 * @private
 */
Ext.define('Ametys.plugins.web.content.actions.DeleteContentAction', {
	singleton: true,
	
	/**
	 * Action function to be called by the controller.
	 * Will delete the contents registered by the controller.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	act: function (controller)
	{
		var contentIds = controller.getContentIds();
		
		if (contentIds.length > 0)
		{
			var contentTargets = controller.getMatchingTargets();
			var validContentTargets = [];
			var contentTitles = [];
			var sharedContentTitles = [];
			
			Ext.Array.forEach (contentTargets, function (contentTarget) {
				if (Ext.Array.contains (contentIds, contentTarget.getParameters().id))
				{
					validContentTargets.push(contentTarget);
					contentTitles.push (contentTarget.getParameters().title);
					
					if (contentTarget.getParameters().hasShares)
					{
						sharedContentTitles.push(contentTarget.getParameters().title);
					}
				}
			});
			
			if (sharedContentTitles.length > 0)
			{
				Ametys.Msg.confirm("{{i18n plugin.cms:CONTENT_DELETE_LABEL}}", 
						"{{i18n PLUGINS_WEB_CONTENT_DELETE_HAS_SHARES_CONFIRM_1}}<b>" + contentTitles.join(', ') + "</b>{{i18n PLUGINS_WEB_CONTENT_DELETE_HAS_SHARES_CONFIRM_2}}",
						Ext.bind(this._deleteConfirm, this, [controller, contentIds], 1),
						this
				);
			}
			else
			{
				Ametys.Msg.confirm("{{i18n plugin.cms:CONTENT_DELETE_LABEL}}", 
						"{{i18n plugin.cms:CONTENT_DELETE_CONFIRM}}" + contentTitles.join(', ') + ' ?', 
						Ext.bind(this._deleteConfirm, this, [controller, contentIds], 1),
						this
				);
			}
		}
	},
	
	/**
	 * Callback function invoked after the #act confirm box is closed
	 * @param {String} answer Id of the button that was clicked
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the #act function
	 * @param {String[]} contentIds The content identifiers
	 * @private
	 */
	_deleteConfirm: function (answer, controller, contentIds)
	{
		if (answer == 'yes')
		{
			Ametys.cms.content.ContentDAO.trashContents (contentIds, controller.getMatchingTargets());
		}
	}
	
});