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

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

import gov.va.vinci.dart.biz.Comment;
import gov.va.vinci.dart.biz.NestableComment;
import gov.va.vinci.dart.db.CommentDAO;

public class CommentDAOMock implements CommentDAO {

	private static final HashMap<Integer,Comment> IDHash = new HashMap<Integer,Comment>();
	private static boolean initialized = false;
	private static int idCounter = 1;

	@Override
	public void save(Comment comment) {
		if (comment == null) {
			throw new IllegalArgumentException();
		}
		
		initializeCommentHash();
		
		if (comment.getId() == 0) {
			comment.setId(idCounter++);
		}
		
		if (comment.getNextComments() == null) {
			comment.setNextComments(new HashSet<Comment>());
		}
		
		// Hibernate does this automatically
		if (comment.getPreviousComment() != null) {
			if (comment.getPreviousComment().getNextComments() == null) {
				comment.getPreviousComment().setNextComments(new HashSet<Comment>());
			}
			if (comment.getPreviousComment().getNextComments().contains(comment) == false){ 
				comment.getPreviousComment().getNextComments().add(comment);
			}
		}
		
		// Hibernate does this automatically
		if (comment.getRequest() != null && comment.getRequest().getComments() != null && comment.getRequest().getComments().contains(comment) == false) {
			comment.getRequest().getComments().add(comment);
		}
		
		IDHash.put(comment.getId(), comment);
	}

	@Override
	public Comment findById(int commentId) {
		initializeCommentHash();
		
		return IDHash.get(commentId);
	}

	@Override
	public List<Comment> listByActivityId(int activityId) {
		initializeCommentHash();
		
		List<Comment> result = new ArrayList<Comment>();
		
		for (Integer id: IDHash.keySet()) {
			Comment comment = IDHash.get(id);
			if (comment.getRequest().getActivity().getId() == activityId) {
				result.add(comment);
			}
		}

		return result;	
	}

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

		return result;	
	}

	@Override
	public List<NestableComment> listByRequestId(int requestId) {
		initializeCommentHash();
		
		return new NestableCommentDAOMock(requestId).build();
	}

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

	@Override
	public void setPreviousComment(int commentId, int previousCommentId) {

		// this won't prune the next comment set of the 
		Comment c1 = IDHash.get(commentId);
		Comment c2 = IDHash.get(previousCommentId);

		if (c1.getPreviousComment() != null) {
			Comment c3 = IDHash.get(c1.getPreviousComment().getId());
			c3.getNextComments().remove(c1);
		}
		
		c2.getNextComments().add(c1);
	}
	

}
