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.OperationalRequest;
import gov.va.vinci.dart.biz.OperationalStudy;
import gov.va.vinci.dart.biz.Participant;
import gov.va.vinci.dart.biz.Person;
import gov.va.vinci.dart.db.OperationalStudyDAO;
import gov.va.vinci.dart.service.DartObjectFactory;

public class OperationalStudyDAOMock implements OperationalStudyDAO {

	private static final HashMap<Integer,OperationalStudy> IDHash = new HashMap<Integer,OperationalStudy>();
	
	private static boolean initialized = false;

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

	@Override
	public OperationalStudy findById(int activityId) {
		initializeStudyHash();

		 return IDHash.get(activityId);
	}

	@Override
	public List<OperationalStudy> listAll() {
		List<OperationalStudy> result = new ArrayList<OperationalStudy> ();

		initializeStudyHash();

		if (IDHash.size() > 0) {
			for (Integer id: IDHash.keySet()) {
				result.add(IDHash.get(id));
			}
		}
		
		return result;
	}
	
	@Override
	public OperationalStudy findByShortName(String name) {
		initializeStudyHash();

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

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

		try {
			initializeStudyHash0();
		}
		catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}
		catch (ValidationException e) {
			e.printStackTrace();
		}
	}
	
	private void initializeStudyHash0() throws ValidationException, ObjectNotFoundException{

		OperationalStudy rs = OperationalStudy.create("test activity 2", new Date(), new Date(), "official name 2", "vhaislduboij", 1004);
		Person pers = DartObjectFactory.getInstance().getPersonDAO().findById(1004);
		OperationalRequest req = OperationalRequest.create("test request 2", 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);

	}

}
