/*
 *  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 restore old version of a content
 * @private
 */
Ext.define('Ametys.plugins.cms.content.actions.RestoreRevisionAction', {
	singleton: true,
	
	/**
	 * Action function to be called by the controller.
	 * Will restore the old revision of the content registered by the controller.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	act: function (controller)
	{
		var contentTargets = controller.getMatchingTargets();
		
		if (contentTargets.length > 0)
		{
			Ametys.Msg.confirm("{{i18n CONTENT_RESTORE_LABEL}}", 
					"{{i18n CONTENT_RESTORE_CONFIRM}}", 
					Ext.bind(this._restoreConfirm, this, [controller, contentTargets[0]], 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 {Ametys.message.MessageTarget} contentTarget The concerned content targets
	 * @private
	 */
	_restoreConfirm: function (answer, controller, contentTarget)
	{
		if (answer == 'yes')
		{
			var actionId = controller.getInitialConfig('workflow-action-id');
			
			Ametys.data.ServerComm.send({
				plugin: 'cms',
				url: 'do-action/' + actionId,
				parameters: {contentId: contentTarget.getParameters().id, contentVersion: contentTarget.getParameters().version}, 
				priority: Ametys.data.ServerComm.PRIORITY_MAJOR,
				waitMessage: true,
				callback: {
					handler: this._restoreCallback,
					scope: this,
					arguments: [contentTarget.getParameters().id]
				}
			});
		}
	},
	
	/**
	 * Callback function called after restore action is processed.
	 * Fires Ametys.message.Message.WORKFLOW_CHANGED message for concerned contents
	 * @param {Object} response The XML response provided by the {@link Ametys.data.ServerComm}
	 * @param {Object} args The callback parameters passed to the {@link Ametys.data.ServerComm#send} method
	 * @private
	 */
	_restoreCallback: function (response, args)
	{
		if (Ametys.data.ServerComm.handleBadResponse("{{i18n CONTENT_RESTORE_ERROR}}", response, this.self.getName()))
        {
            return;
        }
		
		var success = Ext.dom.Query.selectValue ('> ActionResult > success', response) == "true";
		
		var workflowErrors = Ext.dom.Query.select ('> ActionResult > workflowValidation > error', response);
		if (!success && workflowErrors.length > 0)
		{
			var errorMsg = "{{i18n CONTENT_RESTORE_ERROR}}";
			errorMsg += '<ul>';
			for (var i=0; i < workflowErrors.length; i++)
			{
				errorMsg += '<li>' + Ext.dom.Query.selectValue("", workflowErrors[i]) + '</li>';
			}
			errorMsg += '</ul>';
			
			Ametys.Msg.show({
				title: "{{i18n CONTENT_RESTORE_LABEL}}",
				msg: errorMsg,
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
			return;
		}
		
		var brokenReferences = Ext.dom.Query.select('> ActionResult > brokenReferences > *', response);
		if (brokenReferences.length > 0)
		{
		    var errorMsg = "{{i18n CONTENT_RESTORE_BROKEN_REFERENCES_WARNING}}";
            errorMsg += '<ul>';
            for (var i = 0; i < brokenReferences.length; i++)
            {
                errorMsg += '<li>' + Ext.dom.Query.selectValue('', brokenReferences[i]) + '</li>';
            }
            errorMsg += '</ul>';
            
            Ametys.Msg.show({
                title: "{{i18n CONTENT_RESTORE_LABEL}}",
                msg: errorMsg,
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.WARNING
            });
            return;
		}
		
		Ametys.cms.content.ContentDAO.getContent(args[0], Ext.bind(this._sendEventMessages, this));
	},
	
	/**
	 * Creates and fires a Ametys.message.Message#WORKFLOW_CHANGED and Ametys.message.Message#MODIFIED message for the concerned content
	 * @param {Ametys.cms.content.Content} content The concerned content
	 * @private
	 */
	_sendEventMessages: function (content)
	{
		Ext.create("Ametys.message.Message", {
			type: Ametys.message.Message.WORKFLOW_CHANGED,
			
			targets: {
				id: Ametys.message.MessageTarget.CONTENT,
				parameters: { contents: [content] }
			}
		});
		
		Ext.create("Ametys.message.Message", {
			type: Ametys.message.Message.MODIFIED,
			
			targets: {
				id: Ametys.message.MessageTarget.CONTENT,
				parameters: { contents: [content] }
			}
		});
		
		Ametys.tool.ToolsManager.openTool('uitool-content', {id: content.getId()}); // FIXME "edit-workflow-action": controller.getWorkflowActionId()
	}
	
	
});