package com.example.javancss;

import java.io.File;
import java.util.concurrent.locks.Lock;

import com.pmease.quickbuild.extensionpoint.StatisticsSupport;
import com.pmease.quickbuild.model.Build;
import com.pmease.quickbuild.model.Configuration;
import com.pmease.quickbuild.util.BeanUtils;
import com.pmease.quickbuild.util.FileUtils;
import com.pmease.quickbuild.util.LockUtils;

public class JavaNCSSStatisticsSupport implements StatisticsSupport {

	public void collectStatistics(Build build) {
		File metricsFile = new File(build.getPublishDir(), JavaNCSSPlugin.METRICS_FILE);
		if (metricsFile.exists()) {
			MetricsStatistics stats;
			File statsFile = new File(build.getConfiguration().getPublishDir(), 
					JavaNCSSPlugin.STATISTICS_FILE);
			
			// lock the history file for write to prevent it from being read
			Lock lock = LockUtils.lockForWrite(statsFile);
			try {
				if (statsFile.exists())
					stats = (MetricsStatistics) BeanUtils.readFile(statsFile);
				else
					stats = new MetricsStatistics();
				
				MetricsStatistics.Snapshot snapshot = new MetricsStatistics.Snapshot();
				snapshot.setBuildId(build.getId());
				snapshot.setBuildVersion(build.getVersion());
				
				// we do not need to lock report file for read as this file has already 
				// been written while running the build.
				snapshot.setMetrics((Metrics) BeanUtils.readFile(metricsFile));
				stats.getSnapshots().add(snapshot);
				
				BeanUtils.writeFile(stats, statsFile);
			} finally {
				lock.unlock();
			}
		}
	}

	public void cleanupStatistics(Configuration configuration) {
		File historyFile = new File(configuration.getPublishDir(), JavaNCSSPlugin.STATISTICS_FILE);
		Lock lock = LockUtils.lockForWrite(historyFile);
		try {
			FileUtils.deleteFile(historyFile);
		} finally {
			lock.unlock();
		}
		
	}

	public String getStatisticsName() {
		return "Java NCSS";
	}

}
