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

import java.util.HashMap;
import java.util.Map;

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

public class PagesBriefStatistics extends ScriptStatistics {
	private Map<Integer, PageBriefStatistics> map;

	private Map<Integer, PageBriefStatistics> getMap() {
		return map;
	}

	private void setMap(Map<Integer, PageBriefStatistics> map) {
		this.map = map;
	}

	public PagesBriefStatistics() {
		this.setMap(new HashMap<Integer, PageBriefStatistics>());
	}

	public void add(DataStatisticsModel dataUnit) {
		if (dataUnit instanceof AgentPagesBriefModel) {
			add((AgentPagesBriefModel) dataUnit);
		}
	}

	private void add(AgentPagesBriefModel agentPagesBriefModel) {
		for (AgentPageBriefModel unit : agentPagesBriefModel
				.getPageBriefModels()) {
			this.getValueFromMap(unit.getPageId()).add(unit);
		}
	}

	private PageBriefStatistics getValueFromMap(int key) {
		guardMapKeyExists(key);
		return this.getMap().get(key);
	}

	private synchronized void guardMapKeyExists(int key) {
		if (!this.getMap().containsKey(key)) {
			this.getMap().put(key, new PageBriefStatistics());
		}
	}

	public Object getStatistics() {
		ScriptPagesBriefModel scriptPagesBriefModel = new ScriptPagesBriefModel();
		for (Integer key : this.getMap().keySet()) {
			scriptPagesBriefModel.getScriptPageBriefModels().add(
					(ScriptPageBriefModel) this.getValueFromMap(key)
							.getStatistics());
		}
		return scriptPagesBriefModel;
	}

}
