package de.visone.crawl.gui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import de.visone.base.Mediator;
import de.visone.crawl.Settings;
import de.visone.crawl.out.CrawlListener;
import de.visone.crawl.out.TextWriter;
import de.visone.gui.tabs.option.BooleanOptionItem;
import de.visone.gui.tabs.option.FileOptionItem;
import de.visone.gui.tabs.option.OutputFileOptionItem;

/**
 * Crawls a single page and saves its text contents into a file.
 * 
 * @author Joschi
 * @author matthias
 */
public class CrawlTextCard extends AbstractCrawlCard {
	private static final Logger logger = Logger.getLogger(CrawlTextCard.class);

	private static final String CARD_NAME = "crawl text";
	private FileOptionItem out;
	private BooleanOptionItem getXml;

	/**
	 * Create the crawler card.
	 * 
	 * @param mediator
	 *            the {@link Mediator}
	 */
	public CrawlTextCard(final Mediator mediator) {
		super(CARD_NAME, mediator);
	}

	@Override
	protected boolean wantsIntro() {
		return false;
	}

	@Override
	protected void fillAdditionalImportantOptions() {
		out = new OutputFileOptionItem("output file", ".txt");
		addOptionItem(out, "output file");
	}

	@Override
	protected void fillAdditionalObscureOptions() {
		getXml = new BooleanOptionItem();
		getXml.setValue(false);
		if (Mediator.DEVEL_MODE)
			addOptionItem(getXml, "save as XML");
	}

	@Override
	protected Settings createSettings(final String url) {
		final Settings s = super.createSettings(url);
		s.maxDepth = 0;
		s.doLinks = false;
		s.xmlText = getXml.getValue();
		return s;
	}

	/** {@inheritDoc} */
	@Override
	public CrawlListener getCrawlListener(final Settings s) {
		final File outputFile = out.getValue();
		if (outputFile == null) {
			JOptionPane.showMessageDialog(null,
					"please specify an output file", "no output file",
					JOptionPane.ERROR_MESSAGE);
			out.getComponent().requestFocusInWindow();
			return null;
		}

		try {
			return new TextWriter(new PrintStream(outputFile));
		} catch (final FileNotFoundException e) {
			logger.error("cannot create output file " + outputFile, e);
			JOptionPane.showMessageDialog(null,
					"the output file could not be created",
					"cannot create output file", JOptionPane.ERROR_MESSAGE);
			return null;
		}
	}

	@Override
	protected boolean getHaltOnError() {
		return true;
	}
}
