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

/**
 * Class handling PDF insertion in inline editor.
 * @private
 */
Ext.define('Ametys.plugins.flipbook.editor.Flipbook', {
	singleton: true,

    /**
     * Initialize function to add a link handler for flipbook attachmed file
     * @param controller {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    initializeAttachmentLink: function (controller)
    {
        Ametys.plugins.cms.editor.Links.addLinkHandler ('attachment-content-flipbook', Ext.create('Ametys.plugins.cms.editor.Links.AttachmentLinkHandler', {}));
    },

    /**
     * Initialize function to add a link handler for flipbook attached file
     * @param controller {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    initializeExplorerLink: function (controller)
    {
        Ametys.plugins.cms.editor.Links.addLinkHandler ('explorer-flipbook', Ext.create('Ametys.plugins.cms.editor.Links.ResourceLinkHandler', {}));
    },

	/**
	 * Insert a local pdf
	 * @param controller {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	insertLocalPDF: function(controller)
	{
		var contentTarget = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget(Ametys.message.MessageTarget.CONTENT);
		if (contentTarget)
		{
			var ownerId = contentTarget.getParameters().id,
				link = this._getLink(),
				currentId = (link && link.getAttribute('data-ametys-type') == 'attachment-content-flipbook') ? link.getAttribute('data-ametys-href') : null;
				
			Ametys.cms.uihelper.ChooseAttachmentFile.open({
				iconCls: [controller.getInitialConfig('icon-glyph'), controller.getInitialConfig('icon-decorator')].join(' '),
				title: "{{i18n PLUGINS_FLIPBOOK_EDITOR_INSERT_LOCAL_DIALOG_LABEL}}",
				helpmessage: "{{i18n PLUGINS_FLIPBOOK_EDITOR_INSERT_LOCAL_DIALOG_DESCRIPTION}}",
				ownerId: ownerId,
				callback: Ext.bind(this._insertLocalPDFCb, this),
				filter: Ametys.explorer.tree.ExplorerTree.PDF_FILTER,
				value: currentId,
				allowCreation: true,
				rightContext: '/contents/' + contentTarget.getParameters().name
			});
		}
		else
		{
			Ametys.log.ErrorDialog.display({
				title: "{{i18n plugin.web:PLUGINS_WEB_EDITOR_LINK_ERRORCONTENT_LABEL}}",
				text: "{{i18n plugin.web:PLUGINS_WEB_EDITOR_LINK_ERRORCONTENT_DESCRIPTION}}",
				category: 'Ametys.plugins.flipbook.editor.Flipbook.insertLocalPDF' 
			});
		}
	},
	
	/** Callback called after the validation of the choose attachment dialogbox.
	 * @param {String} id The id of the file
	 * @param {String} filename The name of the file
	 * @param {String} size The size in byte of the file
	 * @param {String} viewHref The url to VIEW the file
	 * @param {String} downloadHref The url to DOWNLOAD the file
	 */
	_insertLocalPDFCb: function(id, filename, size, viewHref, downloadHref)
	{
	    // FIXME "tinyMCE.activeEditor" a better method is to use the field.getEditor()
	    tinyMCE.activeEditor.focus();
		if (id != null)
		{
			var contentTarget = Ametys.message.MessageBus.getCurrentSelectionMessage().getTarget(Ametys.message.MessageTarget.CONTENT);
			if (contentTarget)
			{
				var contentId = contentTarget.getParameters().id,
					fieldTarget = contentTarget.getSubtarget('field');
				
				if (fieldTarget != null)
				{
					var metadataId = fieldTarget.getParameters()['name'].substring("content.input.".length),
						url = id;
					
					tinyMCE.activeEditor.execCommand('mceBeginUndoLevel');
					
					var link = this._getLink();
					if (link == null && tinyMCE.activeEditor.selection.isCollapsed())
					{
						var text = "{{i18n PLUGINS_FLIPBOOK_EDITOR_PDF_LINK_1}} «" + filename + "» {{i18n PLUGINS_FLIPBOOK_EDITOR_PDF_LINK_2}}"; 
						tinyMCE.activeEditor.execCommand('mceInsertContent', false, "<a id='" + id + "'>" + text + "{$caret}</a>");
						
						node = this._getLink();
					}
					
					tinyMCE.activeEditor.execCommand('mceInsertLink', false, {'data-ametys-href': url, href: downloadHref, title: filename, 'class': 'flipbook', 'data-ametys-type': 'attachment-content-flipbook', target: '_blank'});
					tinyMCE.activeEditor.selection.collapse();
					
					tinyMCE.activeEditor.execCommand('mceEndUndoLevel');
				}
			}
		}
	},
	
	/**
	 * Insert a pdf from the resources
	 * @param controller {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	insertResourcesPDF: function(controller)
	{
		Ametys.cms.uihelper.ChooseResource.open({
		    iconCls: [controller.getInitialConfig('icon-glyph'), controller.getInitialConfig('icon-decorator')].join(' '),
		    title: "{{i18n PLUGINS_FLIPBOOK_EDITOR_INSERT_RESOURCES_DIALOG_LABEL}}",
		    helpmessage: "{{i18n PLUGINS_FLIPBOOK_EDITOR_INSERT_RESOURCES_DIALOG_DESCRIPTION}}",
		    callback: Ext.bind(this._insertResourcesPDFCb, this),
		    filter: Ametys.explorer.tree.ExplorerTree.PDF_FILTER
		});
	},
	
	/** Callback called after the validation of the choose resource dialogbox.
	 * @param {String} id The id of the file
	 * @param {String} filename The name of the file
	 * @param {String} size The size in byte of the file
	 * @param {String} viewHref The url to VIEW the file
	 * @param {String} downloadHref The url to DOWNLOAD the file
	 */
	_insertResourcesPDFCb: function(id, filename, size, viewHref, downloadHref)
	{
	    // FIXME "tinyMCE.activeEditor" a better method is to use the field.getEditor()
	    tinyMCE.activeEditor.focus();
		if (id != null)
		{
			var url = id;
			
			tinyMCE.activeEditor.execCommand('mceBeginUndoLevel');
			
			var link = this._getLink();
			if (link == null && tinyMCE.activeEditor.selection.isCollapsed())
			{
				var text = "{{i18n PLUGINS_FLIPBOOK_EDITOR_PDF_LINK_1}} «" + filename + "» {{i18n PLUGINS_FLIPBOOK_EDITOR_PDF_LINK_2}}"; 
				tinyMCE.activeEditor.execCommand('mceInsertContent', false, "<a id='" + id + "'>" + text + "{$caret}</a>");
				
				link = this._getLink();
			}
		
			tinyMCE.activeEditor.execCommand('mceInsertLink', false, {'data-ametys-href': url, 'href': downloadHref, 'title': filename, 'class': 'flipbook', 'data-ametys-type': 'explorer-flipbook', target: '_blank'});
			tinyMCE.activeEditor.selection.collapse();
		
			tinyMCE.activeEditor.execCommand('mceEndUndoLevel');
		}
	},
	
	/**
	 * Get the link node from current cursor position.
	 * @return {HTMLElement} The link node or null if not found.
	 * @private
	 */
	_getLink: function()
	{
		var node = null;
		
		if (tinyMCE.activeEditor != null && tinyMCE.activeEditor.dom != null)
		{
			node = tinyMCE.activeEditor.dom.getParent(tinyMCE.activeEditor.selection.getNode(), 'a');
		}
		
		return node;
	}
});