package hiro.yoshioka.util.ui;

import java.util.ArrayList;

import org.eclipse.jface.contentassist.SubjectControlContentAssistant;
import org.eclipse.jface.contentassist.TextContentAssistSubjectAdapter;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.widgets.Text;

public class MySubjectControlContentAssistant extends
		SubjectControlContentAssistant {

	ArrayList<IPressEnterListener> listener = new ArrayList<IPressEnterListener>();

	MySubjectControlContentAssistProcessor processor;

	public MySubjectControlContentAssistant(final Text text) {
		processor = new MySubjectControlContentAssistProcessor();
		setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
		TextContentAssistSubjectAdapter adapter = new TextContentAssistSubjectAdapter(
				text);
		install(adapter);
		adapter.appendVerifyKeyListener(new VerifyKeyListener() {
			public void verifyKey(VerifyEvent event) {
				if (event.stateMask == SWT.CTRL && event.character == ' ') {
					try {
						showPossibleCompletions();
						event.doit = false;
					} catch (RuntimeException e) {
						e.printStackTrace();
					}

				} else if (event.character == '\r' || event.character == '\n') {
					for (int i = 0; i < listener.size(); i++) {
						// System.out.println("text[" + i + "]=" + text);
						// System.out.println("event.text=" + event.text);
						// System.out.println("event.data=" + event.data);
						listener.get(i).pressEnter(text.getText());
					}
					event.doit = false;
				}
			}
		});
	}

	public void addPressEnterListener(IPressEnterListener obj) {
		listener.add(obj);
	}

	public void setProposalStrings(String[] propstr) {
		processor.fCompletionStrings = propstr;
	}
}
