package de.visone.nlpext.gui;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import de.visone.base.Mediator;
import de.visone.ext.nlp.PennTreeAlgorithm;
import de.visone.gui.tabs.option.TextOptionItem;
import de.visone.nlpext.network.TextNetwork;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.parser.lexparser.LexicalizedParserQuery;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
import edu.stanford.nlp.trees.Tree;

/**
 * Card to visualize a parsed sentence in visone.
 * 
 * @author unknown
 * @author matthias
 */
public class PennTreeCard extends ParserNetworkCard {
	private static final String SENTENCE_LABEL = "sentence";

	private TextOptionItem sentence;
	private final PennTreeAlgorithm algorithm;

	/**
	 * @param mediator
	 *            the {@link Mediator}
	 */
	public PennTreeCard(final Mediator mediator) {
		super(mediator, "show penn tree");
		algorithm = new PennTreeAlgorithm();
	}

	@Override
	public String getApplyText() {
		return "create penn tree";
	}

	public String getParseTree(final String sentence, final Mediator mediator) {
		loadParser();

		// TODO destroy the network
		if (parser == null)
			return null;

		final List<List<HasWord>> sentences = MaxentTagger
				.tokenizeText(new StringReader(sentence));
		if (sentences.isEmpty())
			return null;
		// it's supposed to be just one sentence so just concatenate
		// everything...
		final List<HasWord> words = new ArrayList<HasWord>();
		for (final List<HasWord> sent : sentences)
			words.addAll(sent);

		final LexicalizedParserQuery parserQuery = parser.parserQuery();
		if (parserQuery.parse(words)) {
			final Tree parsedTree = parserQuery.getBestParse();
			return parsedTree.pennString();
		}

		return null;
	}

	@Override
	protected void runAlgorithm() {
		final String sentence = getSentence();
		final String parseTree = getParseTree(sentence, mediator);
		algorithm.runAlgorithm(parseTree, mediator);
	}

	private String getSentence() {
		return sentence.getValue();
	}

	@Override
	protected void fillParameterPanel() {
		addParserOptions();

		addHeading("sentence to parse and visualize");
		sentence = new TextOptionItem();
		sentence.setValue("this is just an example of what a sentence could look like.");
		addOptionItem(sentence, SENTENCE_LABEL);
	}

	@Override
	public TextNetwork getTextNetwork() {
		throw new UnsupportedOperationException();
	}
}
