package org.bench4q.master.domain.valueobject.datastatistics;

import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;

/**
 * 
 * @author coderfengyun :This class is only statistics for One page, should
 *         construct it once each page;
 * @Tip countFromBegin : Because of the statistics means that just accumulate
 *      the "countFromBegin" field of AgentPageBriefModel, so I can just take it
 *      as a temperary field for this class
 */
public class PageBriefStatistics extends ScriptStatistics {
	private long countFromBegin;
	private long maxResponseTimeFromBegin;
	private long minResponseTimeFromBegin;
	private long totalResponseTimeThisTime;
	private long countThisTime;
	private long latestResponseTime;

	public PageBriefStatistics() {
		resetTemperaryFields();
		this.maxResponseTimeFromBegin = Long.MIN_VALUE;
		this.minResponseTimeFromBegin = Long.MAX_VALUE;
	}

	private void resetTemperaryFields() {
		this.totalResponseTimeThisTime = 0;
		this.countThisTime = 0;
		this.countFromBegin = 0;
	}

	public void add(DataStatisticsModel dataUnit) {
		if (!(dataUnit instanceof AgentPageBriefModel)) {
			return;
		}
		add((AgentPageBriefModel) dataUnit);
	}

	private void add(AgentPageBriefModel pageBriefModel) {
		this.countFromBegin += pageBriefModel.getCountFromBegin();
		this.countThisTime += pageBriefModel.getCountThisTime();
		this.totalResponseTimeThisTime += pageBriefModel
				.getTotalResponseTimeThisTime();
		this.latestResponseTime = pageBriefModel.getLatestResponseTime();
		if (pageBriefModel.getMaxResponseTimeFromBegin() > this.maxResponseTimeFromBegin) {
			this.maxResponseTimeFromBegin = pageBriefModel
					.getMaxResponseTimeFromBegin();
		}
		if (pageBriefModel.getMinResponseTimeFromBegin() < this.minResponseTimeFromBegin) {
			this.minResponseTimeFromBegin = pageBriefModel
					.getMinResponseTimeFromBegin();
		}
	}

	public Object getStatistics() {
		ScriptPageBriefModel result = new ScriptPageBriefModel();
		result.setCountFromBegin(this.countFromBegin);
		result.setLatestResponseTime(this.latestResponseTime);
		result.setMaxResponseTimeFromBegin(this.maxResponseTimeFromBegin);
		result.setMinResponseTimeFromBegin(this.minResponseTimeFromBegin);
		if (this.countThisTime > 0) {
			result.setAverageResponseTimeThisTime(this.totalResponseTimeThisTime
					/ this.countThisTime);
		}
		resetTemperaryFields();
		makeUpResultModelWithSamplingTime(result);
		return result;
	}

}
