/*
 *  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.
 */
 
/**
 * Enables to add a word definition from the current text selection.
 * @private
 */
Ext.define('Ametys.plugins.glossary.editor.GlossaryEditor', {
	singleton: true,
	
	/**
	 * @private {String} _selection The current selected text
	 */
	_selection: '',
	
	/**
	 * Opens the "add definition" dialog, initialized with the selected word.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function.
	 */
	addDefinition: function(controller)
	{
		var targets = Ametys.message.MessageBus.getCurrentSelectionMessage().getTargets();
		var contentTargets = Ametys.message.MessageTargetHelper.findTargets(targets, function(target) {return target.getId() == 'content'});
		
		if (contentTargets.length > 0 && this._selection.length > 0)
		{
			var contentLang = contentTargets[0].getParameters().lang;
			
			Ametys.plugins.glossary.WordDefinitionDialog.open ({
				lang: contentLang,
				word: this._selection.trim()
			});
		}
	},
	
	/**
	 * Listener when a node is selected
	 * @param {Ametys.cms.editor.EditorButtonController} controller The controller.
	 * @param {Ametys.message.MessageTarget} target The current selection target. Can be null.
	 * @param {HTMLElement} node The current selected node. Can be null.
	 */
	wordSelectionListener: function (controller, target, node)
	{
    	var off = target == null || node == null;
    	
    	if (!off)
    	{
    		this._selection = controller.getCurrentField().getEditor().selection.getContent();
			var disabled = this._selection.length < 1;
    	}
		
    	if (off || disabled)
    	{
    		controller.toggle(false);
    		controller.setDisabled(true);
    		controller.setAdditionalDescription("{{i18n PLUGINS_GLOSSARY_CONTENT_EDITOR_ADD_DEFINITION_DISABLED_DESCRIPTION}}");
	        return;
		}

		controller.toggle(false);
		controller.setDisabled(false);
		controller.setAdditionalDescription('');
	}
	
});