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

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import gov.va.vinci.dart.common.exception.ObjectNotFoundException;
import gov.va.vinci.dart.common.exception.ValidationException;
import gov.va.vinci.dart.biz.DartRequest;
import gov.va.vinci.dart.biz.Participant;
import gov.va.vinci.dart.biz.Person;
import gov.va.vinci.dart.biz.ResearchStudy;
import gov.va.vinci.dart.db.ResearchStudyDAO;
import gov.va.vinci.dart.service.DartObjectFactory;

public class ResearchStudyDAOMock implements ResearchStudyDAO {
	private static final HashMap<Integer,ResearchStudy> IDHash = new HashMap<Integer,ResearchStudy>();
	
	private static boolean initialized = false;

	@Override
	public void save(final ResearchStudy researchStudy) {
		if (researchStudy == null) {
			throw new IllegalArgumentException();
		}
		
		initializeActivityHash();
		
		// have ActivityDAO allocate an Id to the activity
		DartObjectFactory.getInstance().getActivityDAO().save(researchStudy);
		
		IDHash.put(researchStudy.getId(), researchStudy);
	}

	@Override
	public List<ResearchStudy> listAll() {
		List<ResearchStudy> result = new ArrayList<ResearchStudy>();
		
		initializeActivityHash();
		
		for (Integer id: IDHash.keySet()) {
			result.add(IDHash.get(id));
		}

		return result;
	}
	
	@Override
	public ResearchStudy findById(int activityId) {
		initializeActivityHash();

		 return IDHash.get(activityId);
	}

	@Override
	public ResearchStudy findByShortName(String name) {
		initializeActivityHash();

		for (Integer id: IDHash.keySet()) {
			ResearchStudy rs = IDHash.get(id);
			if (name.equals(rs.getName())) {
				return rs;
			}
		}
			
		return null;
	}

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

		try {
			initializeActivityHash0();
		}
		catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}
		catch (ValidationException e) {
			e.printStackTrace();
		}
		
	}
	
	private void initializeActivityHash0() throws ValidationException, ObjectNotFoundException{
		
		ResearchStudy rs = ResearchStudy.create("test activity 1", new Date(), new Date(), "official name", "vhaislduboij");
		Person pers = DartObjectFactory.getInstance().getPersonDAO().findById(1004);
		DartRequest req = DartRequest.create("test request 1 for activity 1", new Date(), new Date(), pers, rs, "vhaislduboij");
		
		if (rs.getRequests().contains(req) == false) {
			rs.getRequests().add(req);
		}
		
		req.setPrimaryLocation(pers.getLocation());
		
		// and that needs a primary investigator
		Participant part = Participant.create(pers, req, pers.getLocation(), true, true, true, true);
		req.getParticipants().add(part);

	}

}
