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

import javax.swing.JDialog;
import javax.swing.JFrame;


public class GECAMedChangeCompletionDialog extends GECAMedSaveCompletionDialog
{
	private static final long serialVersionUID = 1L;
	
	
	private GECAMedAutoCompletion 	completion;
	private boolean 				changed;
	
	
	public GECAMedChangeCompletionDialog(
			JFrame owner,
			GECAMedAutoCompletionTextComponent textComponent,
			GECAMedAutoCompletion completionToChange)
	{
		super(owner, textComponent);
		init(completionToChange);
	}
	
	
	public GECAMedChangeCompletionDialog(
			JDialog owner,
			GECAMedAutoCompletionTextComponent textComponent,
			GECAMedAutoCompletion completionToChange)
	{
		super(owner, textComponent);
		init(completionToChange);
	}
	
	private void init (GECAMedAutoCompletion completionToChange)
	{
		if (completionToChange == null)
			throw new NullPointerException();
		
		this.completion 		= completionToChange;
		
		super.inputTextField.setText(completion.isInputTextSet() ? completion.getInputText() : "");
		super.replacementTextArea.setText(completion.getReplacementText());
		super.markPrivateBox.setSelected(completion.isPrivate());
		
		enableOkButton();
	}
	
	
	@Override
	protected void saveCompletion()
	{
		// replace the old completion, if sth. has changed
		String inputText 		= inputTextField.getText().trim();
		String replacementText 	= replacementTextArea.getText();
		boolean isPrivate		= markPrivateBox.isSelected();
		changed					= false;
		
		if (	   inputText == null 
				|| inputText.equals("")
				|| inputText.equals(replacementText))
			inputText 			= replacementText;
		
		if (	   inputText.equals(completion.getInputText())
				&& replacementText.equals(completion.getReplacementText())
				&& isPrivate == completion.isPrivate())
			// nothing has changed ...
			return;
		
		changed 				= true;
		((GECAMedAutoCompletionTextComponent)view).changeCompletion(completion, inputText, replacementText, isPrivate);
	}
	
	
	public boolean isChanged ()
	{
		return changed;
	}
}
