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

/**
 * Table of contents singleton class for the editor.
 * @private
 */
Ext.define('Ametys.plugins.cms.editor.TableOfContents', {
	singleton: true,
	
	/**
	 * Action function for the 'insert TOC' button controller.
	 * @param {Ametys.cms.editor.EditorButtonController} controller The controller calling this function
	 */
	insert: function(controller)
	{
		var id = Ext.id();
		var editor = controller.getCurrentField().getEditor();
		
		editor.focus();
		editor.execCommand('mceBeginUndoLevel');
		editor.execCommand('mceInsertContent', false, Ametys.plugins.cms.editor.tableofcontents.TableOfContentsConvertorAndValidator.createHTML(id, '', null, true));
		editor.execCommand('mceEndUndoLevel');
		
		var elt = editor.dom.doc.getElementById(id);
		editor.execCommand('mceSelectNode', false, elt);
		elt.removeAttribute('id');
	},
	
	/**
	 * Controller state management
	 * @param {Ametys.cms.editor.EditorButtonController} controller The controller
	 * @param {Ametys.cms.form.widget.RichText} field The current field. Can be null
	 * @param {HTMLElement} node The current selected node. Can be null.
	 */
	insertSelectionListener: function(controller, field, node)
	{
		if (node)
		{
			var elt = field.getEditor().dom.getParent(field.getEditor().selection.getNode(), 'p');
			var sel = field.getEditor().selection.getContent();
			
			if (!elt || sel != '') // enabled if empty selection in a paragraph
			{
				controller.setDisabled(true);
			}
		}
	}
});