package org.bench4q.agent.datacollector.impl;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.bench4q.agent.Main;
import org.bench4q.agent.datacollector.DataCollector;
import org.bench4q.agent.helper.ApplicationContextHelper;
import org.bench4q.agent.scenario.engine.BehaviorResult;
import org.bench4q.agent.storage.StorageHelper;
import org.bench4q.share.models.agent.BehaviorResultModel;

public abstract class AbstractDataCollector implements DataCollector {
	protected StorageHelper storageHelper;

	protected StorageHelper getStorageHelper() {
		return storageHelper;
	}

	public void setStorageHelper(StorageHelper storageHelper) {
		this.storageHelper = storageHelper;
	}

	public AbstractDataCollector() {
		mustDoWhenIniti();
	}

	protected void mustDoWhenIniti() {
		this.setStorageHelper(ApplicationContextHelper.getContext().getBean(
				StorageHelper.class));
	}

	public void add(final BehaviorResult behaviorResult) {
		if (!Main.IS_TO_SAVE_DETAIL) {
			return;
		}
		if (behaviorResult == null) {
			return;
		}
		Runnable runnable = new Runnable() {
			public void run() {
				storageHelper.getLocalStorage().writeFile(
						buildBehaviorResultModel(behaviorResult)
								.getModelString(),
						calculateSavePath(behaviorResult));
			}
		};
		ExecutorService executorService = Executors
				.newSingleThreadScheduledExecutor();
		executorService.execute(runnable);
		executorService.shutdown();
	}

	private BehaviorResultModel buildBehaviorResultModel(
			BehaviorResult behaviorResult) {
		BehaviorResultModel resultModel = new BehaviorResultModel();
		resultModel.setBehaviorId(behaviorResult.getBehaviorId());
		resultModel.setBehaviorName(behaviorResult.getBehaviorName());
		resultModel.setContentLength(behaviorResult.getContentLength());
		resultModel.setContentType(behaviorResult.getContentType());
		resultModel.setEndDate(behaviorResult.getEndDate());
		resultModel.setPluginId(behaviorResult.getPluginId());
		resultModel.setPluginName(behaviorResult.getPluginName());
		resultModel.setResponseTime(behaviorResult.getResponseTime());
		resultModel.setShouldBeCountResponseTime(behaviorResult
				.isShouldBeCountResponseTime());
		resultModel.setStartDate(behaviorResult.getStartDate());
		resultModel.setStatusCode(behaviorResult.getStatusCode());
		resultModel.setSuccessCount(behaviorResult.getSuccessCount());
		resultModel.setFailCount(behaviorResult.getFailCount());
		return resultModel;
	}

	protected abstract String calculateSavePath(BehaviorResult behaviorResult);

	public abstract Object getScenarioBriefStatistics();

	public abstract Map<Integer, BehaviorStatusCodeResult> getBehaviorBriefStatistics(
			int id);

}
