/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.rjconsultores.ventaboletos.dao.CategoriaDAO;
import com.rjconsultores.ventaboletos.entidad.Categoria;

/**
 *
 * @author Administrador
 */
@Repository("categoriaDAO")
public class CategoriaHibernateDAO extends GenericHibernateDAO<Categoria, Integer>
        implements CategoriaDAO {

    @Autowired
    public CategoriaHibernateDAO(@Qualifier("sessionFactory") SessionFactory factory) {
        setSessionFactory(factory);
    }

    @Override
    public List<Categoria> obtenerTodos() {
        Criteria c = getSession().createCriteria(getPersistentClass());
        c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));
        c.addOrder(Order.asc("desccategoria"));

        return c.list();
    }

    public List<Categoria> buscar(String desccategoria) {
        Criteria c = getSession().createCriteria(getPersistentClass());
        c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));
        c.add(Restrictions.eq("desccategoria", desccategoria));

        return c.list();
    }

	@Override
	public List<Categoria> buscarCategoriaPesquisada(String desccategoria) {
		Criteria c = getSession().createCriteria(getPersistentClass());
        c.add(Restrictions.eq(ACTIVO, Boolean.TRUE));
        c.add(Restrictions.ilike("desccategoria", desccategoria, MatchMode.ANYWHERE));

        return c.list();
	}

	@Override
	public List<String> buscarCategoriaOrgaoConcedente(String orgaoConcedente) {

		StringBuilder sql = new StringBuilder();

		orgaoConcedente = "'%" + orgaoConcedente + "%'";

		sql.append("SELECT DISTINCT     c.desccategoria ");
		sql.append(" FROM Categoria c ");
		sql.append(" 	left join categoria_descuento cd on (c.categoria_id = cd.categoria_id and cd.activo=1 ) ");
		sql.append("	left join CATEGORIA_ORGAO co on (co.categoriactrl_id = cd.categoriactrl_id and co.activo = 1) ");
		sql.append("	left join orgao_concedente oc on (co.orgaoconcedente_id = oc.orgaoconcedente_id) ");
		sql.append(" WHERE oc.descorgao like '%DAER%' or oc.descorgao LIKE 'TODOS' ");

		Query sq = getSession().createSQLQuery(sql.toString());
		
		return sq.list();
	}
}
