package gov.va.vinci.dart.db.mock;

import java.util.HashMap;

import gov.va.vinci.dart.common.exception.ObjectNotFoundException;
import gov.va.vinci.dart.biz.Participant;
import gov.va.vinci.dart.db.ParticipantDAO;

public class ParticipantDAOMock implements ParticipantDAO {

	private static HashMap<Integer,Participant> IDHash = new HashMap<Integer,Participant>();
	private static boolean initialized = false;
	private static int idCounter = 1;
	
	@Override
	public void save(Participant participant) {
		if (participant == null) {
			throw new IllegalArgumentException();
		}
	
		initializeParticipantHash();
		
		if (participant.getId() == 0) {
			participant.setId(idCounter++);
		}
	
		if (participant.getRequest() != null && participant.getRequest().getParticipants() != null && participant.getRequest().getParticipants().contains(participant) == false) {
			participant.getRequest().getParticipants().add(participant);			
		}
		
		IDHash.put(participant.getId(), participant);
	}

	@Override
	public void delete(Participant participant) {
		if (participant == null) {
			throw new IllegalArgumentException();
		}
		
		initializeParticipantHash();
		
		IDHash.remove(participant.getId());
	}

	@Override
	public Participant findById(int participantId) {
		initializeParticipantHash();
		
		return IDHash.get(participantId);
	}

	@Override
	public Participant find(int requestId, int personId, int locationId) {
		initializeParticipantHash();
		
		for (Integer id: IDHash.keySet()) {
			Participant part = IDHash.get(id);
			if (part.getRequest().getId() == requestId
					&& part.getPerson().getId() == personId
					&& part.getLocation().getId() == locationId) {
				return part;
			}
		}
		
		return null;
	}

	@Override
	public Participant findPrincipalInvestigator(int requestId, int locationId)
			throws ObjectNotFoundException {
		initializeParticipantHash();
		
		for (Integer id: IDHash.keySet()) {
			Participant part = IDHash.get(id);
			if (part.getRequest().getId() == requestId
					&& part.getPrincipalInvestigator().booleanValue() == true
					&& part.getLocation().getId() == locationId) {
				return part;
			}
		}

		return null;
	}

	private void initializeParticipantHash() {
		if (initialized == true) {
			return;
		}
		initialized = true;
	}
	

}
