package com.graph;

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

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class QuoteDAOImpl implements QuoteDAO{
	@Autowired
	private SessionFactory sessionFactory;

	protected Session getSession(){
		return this.sessionFactory.openSession();
	}
	
	@Override
	public List<QuotePE> getLastFrom(String sigle, int last){
		Session session = getSession();
		
		Criteria criteria = session.createCriteria(QuotePE.class);
		criteria.add(Restrictions.eq("symbol", sigle));
		criteria.addOrder(Order.desc("id"));
		criteria.setMaxResults(last);
		
		List<QuotePE> lPe = criteria.list();
		
		session.close();

		return lPe;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<QuotePE> getList() {
    	Session session = getSession();
    	Criteria criteria = session.createCriteria(QuotePE.class);
		List<QuotePE> list = (List<QuotePE>)criteria.list();
		session.close();
		
		return list;
	}

	@Override
	public void save(QuotePE pe) {
    	Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.persist(pe);
		tx.commit();
		session.close();
	}

	@Override
	public QuotePE getLast(String sigle) {
		Session session = getSession();

		DetachedCriteria  maxDate = DetachedCriteria.forClass(QuotePE.class);
		maxDate.add(Restrictions.eq("symbol", sigle));
		maxDate.setProjection(Projections.max("creationDateTime"));
		
    	Criteria criteria = session.createCriteria(QuotePE.class);
    	criteria.add(Restrictions.eq("symbol", sigle));
    	criteria.add(Property.forName("creationDateTime").eq(maxDate));
    	
		QuotePE pe = (QuotePE) criteria.uniqueResult();
		session.close();
		
		return pe;
	}
	
	@Override
	public QuotePE getFromDate(Date dateStartStep, Date dateEndStep){
		Session session = getSession();
		String requete = "FROM QuotePE "
				+ "WHERE creationDateTime <= :dateMin "
				+ "AND creationDateTime > :dateMax "
				+ "ORDER BY creationDateTime ASC ";
		
		Query query = session.createQuery(requete);
		
		query.setTimestamp("dateMin", dateStartStep);
		query.setTimestamp("dateMax", dateEndStep);
		query.setFirstResult(0);
		query.setMaxResults(1);
		query.uniqueResult();
		
		List<QuotePE> lpe = (List<QuotePE>) query.list();
		

		session.close();
		
		if(lpe.isEmpty())
			return null;
		else 
			return lpe.get(0);
		
		
	}

	@Override
	public QuotePE get(long id) {

		Session session = getSession(); 
		
		QuotePE pe = (QuotePE) session.get(QuotePE.class, id);
		
		session.close();
		
		return pe;
	}
	
	
}