package jp.igapyon.jcfa.util;

import java.util.Map;

import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;

public class JcfaEclipseUtil {
	/**
	 * Format source using eclipse.
	 * 
	 * @param source
	 *            Input source.
	 * @return Formatted source.
	 */
	public static String formatSource(final String source) {
		if (false)
			System.out.println("TRACE: " + source);

		final Map options = DefaultCodeFormatterConstants
				.getEclipseDefaultSettings();

		options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
				JavaCore.VERSION_1_7);
		options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);

		options.put(
				DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
				DefaultCodeFormatterConstants.createAlignmentValue(true,
						DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
						DefaultCodeFormatterConstants.INDENT_ON_COLUMN));

		final CodeFormatter cf = ToolFactory.createCodeFormatter(options);
		cf.createIndentationString(4);
		final TextEdit te = cf.format(CodeFormatter.K_COMPILATION_UNIT
				| CodeFormatter.F_INCLUDE_COMMENTS, source, 0, source.length(),
				0, null);
		if (te == null) {
			return source;
		}
		IDocument doc = new Document(source);
		try {
			te.apply(doc);

			if (false)
				System.out.println("TRACE: " + doc.get());

			return doc.get();
		} catch (MalformedTreeException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		} catch (BadLocationException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
	}
}
