package gov.va.vinci.dart.db;

import javax.persistence.Query;

import gov.va.vinci.dart.biz.NestableComment;
import gov.va.vinci.dart.db.util.NativeQueryDAO;

public class NestableCommentDAO extends NativeQueryDAO<NestableComment> {

	private int requestId;
	
	public NestableCommentDAO(int requestId) {
		this.requestId = requestId;
	}
	
	public String getQueryText() {
		return "select c.RequestID"+
				", c.ID"+
				", coalesce(p.ID, c.ID) as ParentID"+
				", case when c.PreviousID is null then 'Parent' else 'Child' end as relation"+
				", c.version"+
				", c.Description"+
				", c.Text"+
				", per.fullname" +
				", c.createdon" +
				", r.activityid" +
				" from hib.Comment c" +
				" left join hib.Comment p on c.PreviousID = p.ID" +
				" inner join hib.person per on per.name=upper(c.createdby)" +
				" inner join hib.request r on r.id=c.requestid" +
				" where c.requestid = ?"+
				" order by ParentID, ID";
	}
	
	public void populateParameters(final Query q) {
		q.setParameter(1, requestId); 
	}

	public NestableComment buildResult(final Object obj) {
		NestableComment comment = new NestableComment();

		if (obj.getClass().isArray()) {
			Object[] two = (Object[]) obj;
			
			comment.setRequestId((Integer)two[0]);
			comment.setId((Integer)two[1]);
			comment.setParentId((Integer)two[2]);
			comment.setRelation((String)two[3]);
			comment.setVersion((Integer)two[4]);
			comment.setDescription((String)two[5]);
			comment.setText((String)two[6]);
			comment.setCreatedBy((String)two[7]);
			comment.setCreatedOn((java.sql.Timestamp)two[8]);
			comment.setActivityId((Integer)two[9]);
			
			return comment;
		}
		else {
			throw new IllegalStateException("Cannot parse JDBC query result");
		}

	}
}
