package com.example.javancss;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.hibernate.validator.constraints.NotEmpty;

import com.pmease.quickbuild.Context;
import com.pmease.quickbuild.QuickbuildException;
import com.pmease.quickbuild.annotation.Editable;
import com.pmease.quickbuild.annotation.Scriptable;
import com.pmease.quickbuild.stepsupport.Step;
import com.pmease.quickbuild.util.BeanUtils;
import com.pmease.quickbuild.util.FileUtils;

@Editable(name="JavaNCSS Report", category="Publish")
public class JavaNCSSPublishStep extends Step {

	private static final long serialVersionUID = 1L;
	
	private String reportPath;

	@Editable(order=1000, name="JavaNCSS Report Path", description="Specify path to " +
			"JavaNCSS xml report file. A non-absolute path will be considered to be " +
			"relative to current workspace directory. If left empty, the workspace " +
			"directory itself will be assumed.")
	@Scriptable
	@NotEmpty
	public String getReportPath() {
		return reportPath;
	}

	public void setReportPath(String reportPath) {
		this.reportPath = reportPath;
	}

	@Override
	public void run() {
		Context.getLogger().info("Publishing JavaNCSS metrics report...");

		File rawReportFile = FileUtils.resolvePath(Context.getConfiguration().getWorkspaceDir(), 
				getReportPath());
		Document dom;
		try {
			dom = new SAXReader().read(rawReportFile);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
		int sourceLines = Integer.valueOf(
				dom.selectSingleNode("//javancss/packages/total/ncss").getText());
		int commentLines = Integer.valueOf(dom.selectSingleNode("//javancss/packages/total/single_comment_lines").getText()) + 
				Integer.valueOf(dom.selectSingleNode("//javancss/packages/total/multi_comment_lines").getText()) +
				Integer.valueOf(dom.selectSingleNode("//javancss/packages/total/javadoc_lines").getText());
		
		int commentThreshold = ((PluginSetting)getPlugin().getSetting(true)).getCommentThreshold();
		if (100*commentLines/(sourceLines + commentLines) < commentThreshold)
			throw new QuickbuildException("Source comments are less than " + commentThreshold + "%.");
		
		Metrics metrics = new Metrics();
		metrics.setCommentLines(commentLines);
		metrics.setSourceLines(sourceLines);
		
		File tempFile = FileUtils.createTempFile("javancss");
		try {
			BeanUtils.writeFile(metrics, tempFile);
			Context.getBuild().publish(tempFile, JavaNCSSPlugin.METRICS_FILE);
		} finally {
			FileUtils.deleteFile(tempFile);
		}
	}

}
