package com.example.myplugin;

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 MyMetricsCollector implements StatisticsSupport {

	public void collectStatistics(Build build) {
		/*
		 * This method will be called from server after build finishes. So we can 
		 * access the message file and statistics file directly.
		 */
		File msgFile = new File(build.getPublishDir(), "myplugin/message.txt");
		
		// collect metrics only if message publishing step was executed for this build.
		if (msgFile.exists()) {
			int msgLen = FileUtils.readFileAsString(msgFile).length();
			File statsDir = new File(build.getConfiguration().getPublishDir(), "myplugin");
			Lock lock = LockUtils.lockForWrite(statsDir);
			try {
				FileUtils.createDir(statsDir);
				File statsFile = new File(statsDir, "statistics.xml");
				MyStatistics stats;
				if (statsFile.exists())
					stats = (MyStatistics) BeanUtils.readFile(statsFile);
				else 
					stats = new MyStatistics();
				stats.getMsgLens().put(build.getVersion(), msgLen);
				BeanUtils.writeFile(stats, statsFile);
			} finally {
				lock.unlock();
			}
		}
	}

	public void cleanupStatistics(Configuration configuration) {
		File statsDir = new File(configuration.getPublishDir(), "myplugin");
		Lock lock = LockUtils.lockForWrite(statsDir);
		try {
			FileUtils.deleteDir(statsDir);
		} finally {
			lock.unlock();
		}
	}

	public String getStatisticsName() {
		return "My Metrics";
	}

}
