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

/**
 * Singleton class to handle actions on files for the resources explorer that
 * have specific behavior in the CMS
 * @private
 */
Ext.define('Ametys.plugins.cms.explorer.ResourcesControllerActions.File', {
	singleton: true,
	
	/**
	 * @private
	 * @readonly
	 * @property {RegExp} _targetFilter The regexp that match explorer related target type.
	 */
	_targetFilter : /^(explorer-collection|resource)$/,
	
	//------------------------------------------------------//
	//						ADD								//
	//------------------------------------------------------//
	/**
	 * Function called to upload a new file
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
	 */
	add: function(controller)
	{
		// Search for the first explorer target (explorer node or resource).
		var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), this._targetFilter);
		if (target)
		{
			var message = Ametys.message.MessageBus.getCurrentSelectionMessage();
			var contentTarget = message.getTarget(Ametys.message.MessageTarget.CONTENT);
			
			Ametys.explorer.resources.actions.File.add(
				target.getParameters().id, 
				function (files, parentId, needsReload)
				{
					if (contentTarget && controller.getInitialConfig('workflow-action-id'))
					{
						this._changeContentWorkflow(contentTarget.getParameters().id, controller.getInitialConfig('workflow-action-id'), contentTarget);
					}
				},
				this
			);
		}
	},
	
	//------------------------------------------------------//
	//						RENAME							//
	//------------------------------------------------------//
	/**
	 * Function called to rename a file
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
	 */
	rename: function(controller)
	{
		// Search for the first explorer target (explorer node or resource).
		var target = Ametys.message.MessageTargetHelper.findTarget(controller.getMatchingTargets(), this._targetFilter);
		if (!target)
		{
			return;
		}
		
		// Need to retrieves the resource node to be sure to get the current name.
		var me = this,
			id = target.getParameters().id;
		
		var message = Ametys.message.MessageBus.getCurrentSelectionMessage();
		var contentTarget = message.getTarget(Ametys.message.MessageTarget.CONTENT);
		
        Ametys.explorer.ExplorerNodeDAO.getExplorerNode(id, function(resource) {
            
            var name = resource.getProperties().name;
            
            Ametys.Msg.prompt(
                "{{i18n plugin.explorer:PLUGINS_EXPLORER_FILE_HANDLE_RENAME}}", 
                "{{i18n plugin.explorer:PLUGINS_EXPLORER_FILE_NAME}}", 
                function (btn, text) {
                    if (btn == 'ok')
                    {
                        Ametys.explorer.resources.actions.File.rename(
                            target.getParameters().id,
                            name,
                            text,
                            Ext.bind(me._renameCb, me, [contentTarget, controller.getInitialConfig('workflow-action-id')], true)
                        );
                    }
                },
                me, 
                false,
                name
            );
        });
	},
	
	/**
	 * @private
	 * Callback function called after #rename action is processed
	 * @param {String} id The id of renamed file
	 * @param {String} name The name of the file
	 * @param {Boolean} success True if the renaming succeeded
	 * @param {Ametys.message.MessageTarget} contentTarget The content target. Can be null
	 * @param {Number} actionId The content workflow action id.
	 */
	_renameCb: function(id, name, success, contentTarget, actionId)
	{
		if (success)
		{
			if (contentTarget && actionId)
			{
				this._changeContentWorkflow(contentTarget.getParameters().id, actionId, contentTarget);
			}
		}
	},
	
	//------------------------------------------------------//
	//					REMOVE								//
	//------------------------------------------------------//
	/**
	 * Function called to delete a file
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
	 */
	remove: function(controller)
	{
		// Search for the  explorer targets (explorer node or resource).
		var targets = Ametys.message.MessageTargetHelper.findTargets(controller.getMatchingTargets(), this._targetFilter);
		if (!targets[0])
		{
			return;
		}
		
		var message = Ametys.message.MessageBus.getCurrentSelectionMessage();
		var contentTarget = message.getTarget(Ametys.message.MessageTarget.CONTENT);
		
		var ids = [];
		Ext.Array.forEach(targets, function(target) {
			ids.push(target.getParameters().id);
		});
		
		var me = this;
		Ametys.explorer.resources.actions.File.remove(
			targets[0].getParameters().parentId,
			ids,
			Ext.bind(me._removeCb, me, [contentTarget, controller.getInitialConfig('workflow-action-id')], true)
		);
	},
	
	/**
	 * @private
	 * Callback function called after #remove action is processed
	 * @param {String} parentID The folder parent id
	 * @param {String[]} ids id's of the removed resources
	 * @param {Boolean} success True if success
	 * @param {Ametys.message.MessageTarget} contentTarget The content target. Can be null
	 * @param {Number} actionId The content workflow action id.
	 */
	_removeCb: function(parentID, ids, success, contentTarget, actionId)
	{
		if(success)
		{
			if (contentTarget && actionId)
			{
				this._changeContentWorkflow(contentTarget.getParameters().id, actionId, contentTarget);
			}
		}
	},
	
	//------------------------------------------------------//
	//				Change workflow helper					//
	//------------------------------------------------------//
	
	/**
	 * Executes a workflow action on content
	 * @param {String} contentId The id of the content
	 * @param {Number} actionId The id of workflow action to execute
	 * @param {Ametys.message.MessageTarget} contentTarget The content target
	 * @private
	 */
	_changeContentWorkflow: function(contentId, actionId, contentTarget)
	{
		contentTarget = contentTarget || {
			id: Ametys.message.MessageTarget.CONTENT,
			parameters: {ids: [contentId]}
		};
		
		var me = this;
		var targetCreatedCb = function(targets) {
			var target = targets[0];
			
			var params = {
				contentId: contentId,
				id: contentId, 
				'with-contents': '/_plugins/cms/contents/info'
			};
				
			Ext.create('Ametys.message.Message', {
				type: Ametys.message.Message.WORKFLOW_CHANGING,
				targets: [target]
			});
			
			Ametys.data.ServerComm.send({
				plugin: 'cms',
				url: 'do-action/' + actionId,
				parameters: params,
				priority: Ametys.data.ServerComm.PRIORITY_MAJOR,
				errorMessage: true,
				callback: {
					handler: me._changeContentWorkflowCb,
					scope: me,
					arguments: [target]
				}
			});
		};
		
		if (!(contentTarget instanceof Ametys.message.MessageTarget))
		{
			Ametys.message.MessageTargetFactory.createTargets(contentTarget, targetCreatedCb);
		}
		else
		{
			targetCreatedCb([contentTarget]);
		}
	},
	
	/**
	 * @protected
	 * Callback function called after executing worklow action
	 * Override if specific behavior is needed.
	 * @param {Object} response The XML response provided by the {@link Ametys.data.ServerComm}
	 * @param {Object[]} params The callback parameters passed to the {@link Ametys.data.ServerComm#send} method
	 */
	_changeContentWorkflowCb: function(response, params)
	{
		var contentTarget = params[0];
		
		Ext.create('Ametys.message.Message', {
			type: Ametys.message.Message.WORKFLOW_CHANGED,
			targets: [contentTarget]
		});
	}
});