package lu.tudor.santec.gecamed.core.gui.widgets.autocompletion;

import javax.swing.text.JTextComponent;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.Autocompletion;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.org.fife.ui.autocomplete.AutoCompletionTextComponent;
import lu.tudor.santec.org.fife.ui.autocomplete.Completion;

public class GECAMedAutoCompletionTextComponent extends
		AutoCompletionTextComponent
{
	private static final long serialVersionUID = 1L;
	
	
	public GECAMedAutoCompletionTextComponent(JTextComponent textComponent, String context)
	{
		super(textComponent, context);
	}

	@Override
	protected void initialze(JTextComponent component)
	{
		super.initialze(component);
		
		super.handler = new GECAMedMWACHandler(this);
		hotKeyHandler.setHandler(handler);
		menuHandler.setHandler(handler);
	}
	
	
	@Override
	public boolean addCompletion (Completion completion)
	{
		if (!(completion instanceof GECAMedAutoCompletion))
			return this.addCompletion(completion.getInputText(), completion.getReplacementText(), false);
		else
			return super.addCompletion(completion);
	}
	
	@Override
	public boolean addCompletion (String replacementText)
	{
		return this.addCompletion(null, replacementText, false);
	}
	
	@Override
	public boolean addCompletion (String inputText, String replacementText)
	{
		return this.addCompletion(inputText, replacementText, false);
	}
	
	public boolean addCompletion (String inputText, String replacementText, boolean isPrivate) 
	{
		if (replacementText == null 
				|| "".equals(replacementText.trim()))
			return false;
		inputText = "".equals(inputText) ? null : inputText;
		
		Autocompletion acBean = new Autocompletion(provider.getContext(), inputText, replacementText, isPrivate ? GECAMedModule.getCurrentUser().getId() : null);
		GECAMedAutoCompletion completion = new GECAMedAutoCompletion(provider, acBean);
		
		return super.addCompletion(completion);
	}
	
	@Override
	public boolean changeCompletion(Completion oldCompletion,
			String newInputText, String newReplacementText)
	{
		boolean isPrivate = oldCompletion instanceof GECAMedAutoCompletion
						&& ((GECAMedAutoCompletion)oldCompletion).isPrivate();
		return this.changeCompletion(oldCompletion, newInputText, newReplacementText, isPrivate);
	}
	
	public boolean changeCompletion(Completion oldCompletion,
			String newInputText, String newReplacementText, boolean isPrivate)
	{
		if (oldCompletion instanceof GECAMedAutoCompletion)
			((GECAMedAutoCompletion) oldCompletion).setPrivate(isPrivate);
		GECAMedAutoCompletion newCompletion = new GECAMedAutoCompletion(provider, 
				new Autocompletion(provider.getContext(), newInputText, newReplacementText, isPrivate ? GECAMedModule.getCurrentUser().getId() : null));
		return provider.changeCompletion(oldCompletion, newCompletion);
//		return super.changeCompletion(oldCompletion, newInputText, newReplacementText);
	}
	
}
