/*
 *  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 defining actions of duplication :
 * - copy / paste a content.
 * - copy / paste a set of attributes.
 * @private
 */
Ext.define('Ametys.plugins.cms.content.actions.CopyContentActions', {
	singleton: true,
	
	/**
	 * Action function to be called by the controller.
	 * Allow an user to copy a content, in order to duplicate it later (with a paste action).
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	copyContent: function (controller)
	{
		var contentTarget = controller.getMatchingTargets()[0];
		if (contentTarget)
		{
			Ametys.clipboard.Clipboard.setData (Ametys.message.MessageTarget.CONTENT, contentTarget.getParameters().content);
		}
	},
	
	/**
	 * This action pastes the copied content in a new content
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	pasteContent: function (controller)
	{
		var clipboardData = Ametys.clipboard.Clipboard.getData();
		
		if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.CONTENT)
		{
			Ametys.plugins.cms.content.helper.CopyContent.open ({
				content: clipboardData[0],
				workflowInitActionId: controller.getInitialConfig('creationActionId'),
				workflowEditActionId: controller.getInitialConfig('editionActionId'),
				viewName: controller.getInitialConfig('viewName'),
				viewMode: controller.getInitialConfig('viewMode'),
				checkByDefault: controller.getInitialConfig('checkByDefault'),
				callback: this._displayReport,
				scope: this});
		}
		else
		{
			Ametys.Msg.show({
				title: "{{i18n plugin.cms:CONTENT_COPY_PASTE_AS_NEW_LABEL}}",
				msg: "{{i18n plugin.cms:CONTENT_COPY_PASTE_AS_NEW_NO_COPIED_CONTENT_MSG}}",
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		}
	},
	
	/**
	 * This action pastes the values of copied content in a selection of target contents
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	pasteContentValues: function (controller)
	{
		var clipboardData = Ametys.clipboard.Clipboard.getData();
		
		if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.CONTENT)
		{
			if (!controller.getContentIds() || controller.getContentIds().length == 0)
			{
				Ametys.Msg.show({
					title: "{{i18n plugin.cms:CONTENT_COPY_PASTE_IN_CONTENTS_LABEL}}",
					msg: "{{i18n plugin.cms:CONTENT_COPY_PASTE_IN_CONTENTS_NO_TARGET_CONTENT_MSG}}",
					buttons: Ext.Msg.OK,
					icon: Ext.Msg.ERROR
				});
				return;
			}
			
			Ametys.plugins.cms.content.helper.CopyContentValues.open ({
					sourceContent: clipboardData[0],
					targetContentIds : controller.getContentIds(),
					workflowInitActionId: controller.getInitialConfig('actionId') || controller.getInitialConfig('creationActionId'),
					workflowEditActionId: controller.getWorkflowActionId(),
					viewName: controller.getInitialConfig('viewName'),
					viewMode: controller.getInitialConfig('viewMode'),
					checkByDefault: controller.getInitialConfig('checkByDefault'),
					callback: this._displayReport,
					scope: this});
		}
		else
		{
			Ametys.Msg.show({
				title: "{{i18n plugin.cms:CONTENT_COPY_PASTE_IN_CONTENTS_LABEL}}",
				msg: "{{i18n plugin.cms:CONTENT_COPY_PASTE_IN_CONTENTS_NO_COPIED_CONTENT_MSG}}",
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		}
	},
	
	/**
	 * @private
	 * Displays the copy report to the user in a simple message box.
	 * @param {Object} report The report object containing the list of successful copies and the list of contents or attributes that encountered an error.
	 * @param {Object[]} report.editedContents List of successfully modified contents. Each entry has the following keys : id, title.
	 * @param {Object[]} report.createdContents List of successfully created contents. Each entry has the following keys : id, title.
	 * @param {Object[]} report.failedContentCopies List of content copy errors.
	 * Each entry represents a base content for which the copy has failed and has the following keys : id, title (can be null if not retrieved).
	 * @param {Object[]} report.attributesErrors List of attributes errors.
	 * Each entry represents an attribute for which the copy has failed and has the following keys : label, contentId, contentTitle.
	 */
	_displayReport: function(report)
	{
		function openContentToolLinkDecorator(text, id, isRefTable)
		{
			text = text || unknownTitle;
			
			if (isRefTable === false)
			{
				var onclick = "Ametys.tool.ToolsManager.openTool('uitool-content', {id: '" + id + "'})";
				return '<a href="#" onclick="'+ onclick + '">' + text + '</a>';
			}
			
			return text;
		}
		
		var msg = '';
		var hasErrors = report.failedContentCopies.length > 0 || report.attributesErrors.length > 0;
		var unknownTitle = "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_ERRORS_UNKNOWN_CONTENT_TITLE}}";
		
		if (hasErrors)
		{
			msg += "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_ERRORS_INTRO}}" + '<br/><br/>';
			
			if (report.failedContentCopies.length > 0)
			{
				msg += "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_ERRORS_CONTENTS}}";
				msg += '<ul>';
				Ext.Array.forEach(report.failedContentCopies, function(entry) {
					msg += '<li>' + openContentToolLinkDecorator(entry.title, entry.id, entry.isReferenceTable) + '</li>';
				});
				msg += '</ul>';
			}
			
			if (report.attributesErrors.length > 0)
			{
				msg += "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_ERRORS_ATTRIBUTES}}";
				msg += '<ul>';
				Ext.Array.forEach(report.attributesErrors, function(entry) {
					msg += '<li>' + entry.label + ' (' + openContentToolLinkDecorator(entry.contentTitle, entry.contentId, entry.contentIsSimple) + ')</li>';
				});
				msg += '</ul>';
			}
		}
		else
		{
			msg += "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_SUCCESS_INTRO}}" + '<br/><br/>';
		}
		
		var copiedAttachments = false;
		var editionCount = report.editedContents.length;
		if (editionCount > 0)
		{
			msg += editionCount + ' ' + (editionCount > 1 ? "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_SUCCESS_CONTENTS_EDITED}}" : "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_SUCCESS_CONTENT_EDITED}}") + ' :';
			msg += '<ul>';
			Ext.Array.forEach(report.editedContents, function(entry) {
				copiedAttachments = copiedAttachments || entry.copiedAttachments;
				msg += '<li>' + openContentToolLinkDecorator(entry.title, entry.id, entry.isReferenceTable) + '</li>';
			});
			msg += '</ul>';
		}
		
		var creationCount = report.createdContents.length;
		if (creationCount > 0)
		{
			msg += creationCount + ' ' + (creationCount > 1 ? "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_SUCCESS_CONTENTS_CREATED}}" : "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_SUCCESS_CONTENT_CREATED}}") + ' :';
			msg += '<ul>';
			Ext.Array.forEach(report.createdContents, function(entry) {
				copiedAttachments = copiedAttachments || entry.copiedAttachments;
				msg += '<li>' + openContentToolLinkDecorator(entry.title, entry.id, entry.isReferenceTable) + '</li>';
			});
			msg += '</ul>';
		}
		
		if (report.mainContent)
		{
			copiedAttachments = copiedAttachments || report.mainContent.copiedAttachments;
		}
		
		if (copiedAttachments)
		{
			msg += "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_ATTACHMENTS}}" + '<br/>';
		}
		
		Ext.MessageBox.show({
			title: "{{i18n plugin.cms:CONTENT_COPY_ACTIONS_REPORT_TITLE}}",
			msg: '<div class="report-text">' + msg + '</div>',
			buttons: Ext.Msg.OK,
			icon: hasErrors ? Ext.Msg.WARNING : Ext.Msg.INFO
		});
	}
});