package gov.va.vinci.dart.biz;

import gov.va.vinci.dart.common.ValidationHelper;
import gov.va.vinci.dart.common.exception.ValidationException;
import gov.va.vinci.dart.service.DartObjectFactory;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="Comment", schema="hib")
public class Comment extends BusinessObject {

	@JoinColumn(name = "requestid")
	@ManyToOne(fetch = FetchType.LAZY)
	private Request request;
	
	@JoinColumn(name = "previousid")
	@ManyToOne(fetch = FetchType.LAZY)
	private Comment previousComment;

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "previousComment")
	protected Set<Comment> nextComments;
	
	@Column(name="text", columnDefinition = "varchar(max)")
	private String text;
	
	Comment(){}
	
	public static Comment create(final String description, final Request request, final String userId, final String text) throws ValidationException {
		ValidationHelper.required("Description", description);
		ValidationHelper.required("Request", request);
		ValidationHelper.required("User Id", userId);
		ValidationHelper.required("Text", text);
		
		Comment comment = new Comment();
		comment.createdBy = userId;
		comment.createdOn = new Date();
		comment.request = request;
		comment.description = description;
		comment.name = "comment";
		comment.text = text;

		DartObjectFactory.getInstance().getCommentDAO().save(comment);
		return comment;
	}
	
	public static Comment findById(final int commentId) {
		return DartObjectFactory.getInstance().getCommentDAO().findById(commentId);
	}
	
	public static List<Comment> listByActivityId(final int activityId) {
		return DartObjectFactory.getInstance().getCommentDAO().listByActivityId(activityId);
	}
	
	public static List<NestableComment> listByRequestId(final int requestId) {
		return DartObjectFactory.getInstance().getCommentDAO().listByRequestId(requestId);
	}
	
	public String getText() {
		return text;
	}
	
	public void setText(String text) {
		this.text = text;
	}
	
	public Request getRequest() {
		return request;
	}

	public Comment getPreviousComment() {
		return previousComment;
	}

	public void setPreviousComment(Comment previousComment) {
		DartObjectFactory.getInstance().getCommentDAO().setPreviousComment(getId(), previousComment.getId());
		this.previousComment = previousComment;
	}

	public Set<Comment> getNextComments() {
		return nextComments;
	}
	
	// TESTING ONLY
	public void setNextComments(Set<Comment> comments) {
		this.nextComments = comments;
	}
}
