package ub.scp2.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import ub.scp2.dao.SubjectDao;
import ub.scp2.entities.Subject;
import ub.scp2.entities.Task;
import ub.scp2.entities.User;

/**
 * SubjectDaoImpl.java -this class implements the SubjectDao. This is the Data Acces Object of the Subject entity
 * 
 *
 */
public class SubjectDaoImpl implements SubjectDao, java.io.Serializable {
	SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Retrieve a subject list with all subjects.
	 */
	public List<Subject> getSubjects() {
		 Session session = sessionFactory.getCurrentSession();
		 try{
			 return session.createQuery( "FROM Subject" ).list();
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		return null;
	}

	/**
	 * Save subject in database
	 */
	public void saveSubject(Subject subject) {
		 Session session = sessionFactory.getCurrentSession();
		 try{
			 session.save(subject);
			 session.flush();
		 }catch(Exception e){
			 e.printStackTrace();
		 }

	}

	/**
	 * Delete subject in the database
	 */
	public void deleteSubject(Subject subject) {
		 Session session = sessionFactory.getCurrentSession();
		 try{
			 session.delete(subject);
			 session.flush();
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		
	}

	/**
	 * Update subject in database
	 */
	public void updateSubject(Subject subject) {
		 Session session = sessionFactory.getCurrentSession();
		 try{
			 session.update(subject);
			 session.flush();
		 }catch(Exception e){
			 e.printStackTrace();
		 }	
	}

	/**
	 * Retrive a subject according to the id
	 */
	public Subject getSubjectById(Long subjectId) {
		 try{
			 Session session = sessionFactory.getCurrentSession();
			 Criteria criteria = session.createCriteria(Subject.class);
			 criteria.add(Restrictions.eq("subjectId", subjectId));
			 return (Subject) criteria.uniqueResult();
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 return null;
		
	}
	
	/**
	 * Check for the subject.
	 */
	public boolean subjectTitleExist(String subjectTitle){
		 Session session = sessionFactory.getCurrentSession();
		 try{
			 List<Subject> subject = session.createQuery("FROM Subject WHERE title = ?").setString(0,  subjectTitle).list();
			 return !subject.isEmpty();

		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 return false;
	}



}
