package isrp.hibernate.model.dao;

import isrp.hibernate.model.businessobject.Paper;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class PaperDao extends GenericDao {

	public PaperDao() {
		super(Paper.class);
	}

	public void delete(Paper paper) {
		String hqlDelete = "DELETE Review r WHERE r.paperId = ?";
		session.createQuery(hqlDelete).setLong(0, paper.getId())
				.executeUpdate();
		session.delete(paper);
	}

	@SuppressWarnings("unchecked")
	public List<Paper> getReviewerPapers(int reviewerId, String sortColumn) {
		if (sortColumn == null) {
			sortColumn = "title";
		}
		return (List<Paper>) session.createCriteria(persistedClass).add(
				Restrictions.eq("reviewerId", reviewerId)).addOrder(
				Order.asc(sortColumn)).list();
	}

	@SuppressWarnings("unchecked")
	public List<Paper> getUserPapers(int userId, String sortColumn) {
		if (sortColumn == null) {
			sortColumn = "title";
		}
		return (List<Paper>) session.createCriteria(persistedClass).add(
				Restrictions.eq("authorId", userId)).addOrder(
				Order.asc(sortColumn)).list();
		// return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<Paper> getAllPapers(String sortColumn) {
		if (sortColumn == null) {
			sortColumn = "title";
		}
		return (List<Paper>) session.createCriteria(persistedClass).addOrder(
				Order.asc(sortColumn)).list();
		// return criteria.list();
	}

	public Paper checkIfPathExists(String path) {
		Query query = session.createQuery("FROM Paper where path=?").setString(
				0, path);
		return (Paper) query.uniqueResult();
	}

}
