package org.bench4q.master.domain.service;

import java.util.List;

import org.bench4q.master.domain.entity.Agent;
import org.bench4q.master.domain.repository.AgentRepository;
import org.bench4q.master.infrastructure.highavailable.HighAvailablePool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AgentService {
	public static int AGENT_STATUS_Idel = 1;
	public static int AGENT_STATUS_InRun = 2;
	public static int AGENT_STATUS_BackUp = 3;
	public static int AGENT_STATUS_BreakDown = 4;
	private AgentRepository agentRepository;
	private Object AGENT_LOCK;
	private HighAvailablePool highAvailablePool;

	public AgentService() {
		this.setAgentLock(new Object());
	}

	private HighAvailablePool getHighAvailablePool() {
		return highAvailablePool;
	}

	@Autowired
	private void setHighAvailablePool(HighAvailablePool highAvailablePool) {
		this.highAvailablePool = highAvailablePool;
	}

	private AgentRepository getAgentRepository() {
		return agentRepository;
	}

	@Autowired
	private void setAgentRepository(AgentRepository agentRepository) {
		this.agentRepository = agentRepository;
	}

	public Object getAgentLock() {
		return AGENT_LOCK;
	}

	public void setAgentLock(Object object) {
		this.AGENT_LOCK = object;
	}

	public boolean addAgentToPool(Agent agentWithoutId) {
		if (!this.getAgentRepository().attach(
				Agent.createAgentWithoutId(agentWithoutId))) {
			return false;
		}
		Agent agent = this.getAgentRepository().getAgentBy(
				agentWithoutId.getHostName());
		if (agent == null) {
			return false;
		}
		this.getHighAvailablePool().add(agent);
		return true;
	}

	public boolean removeAgentFromPool(int agentId) {
		this.getHighAvailablePool().remove(
				getAgentRepository().getEntity(agentId));
		return this.getAgentRepository().detach(agentId);
	}

	public List<Agent> loadAgentPoolFromDB() {
		return this.getAgentRepository().loadEntities();
	}

}
