package com.rjconsultores.ventaboletos.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
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.AuditLogDAO;
import com.rjconsultores.ventaboletos.entidad.AuditLog;
import com.rjconsultores.ventaboletos.entidad.AuditModule;
import com.rjconsultores.ventaboletos.entidad.AuditService;

@Repository("auditLogDAO")
public class AuditLogHibernateDAO extends GenericHibernateDAO<AuditLog, Long>
		implements AuditLogDAO {

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

	@Override
	public List<AuditLog> carregarLog(AuditModule modulo) {

		List<AuditService> services = recuperarServices(modulo);

		List<Long> ids = new ArrayList<Long>();

		for (AuditService service : services) {
			ids.add(service.getAuditServiceId());
		}

		Criteria c = getSession().createCriteria(getPersistentClass());
		c.add(Restrictions.in("service.auditServiceId", ids));

		return c.list();
	}

	private List<AuditService> recuperarServices(AuditModule module) {
		Criteria c = getSession().createCriteria(AuditService.class);
		c.add(Restrictions.eq("module", module));

		return c.list();
	}

	@Override
	public List<AuditLog> filtrarLog(AuditLog log) {
		Criteria c = getSession().createCriteria(getPersistentClass());

		if (log.getSistema() != null) {
			c.add(Restrictions.eq("sistema", log.getSistema()));
		}

		if (log.getAction() != null) {
			c.add(Restrictions.eq("action", log.getAction()));
		}

		if (log.getEntityDetail() != null) {
			c.add(Restrictions.like("entityDetail", log.getEntityDetail(), MatchMode.ANYWHERE));
		}

		if (log.getUsuario() != null) {
			c.add(Restrictions.eq("usuario", log.getUsuario()));
		}

		if (log.getService() != null && log.getService().getModule() != null) {
			c.add(Restrictions.eq("service.module", log.getService().getModule()));
		}
		
		if (log.getDataInicio() != null && log.getDataFim() != null) {
			c.add(Restrictions.between("createdDate", log.getDataInicio(), log.getDataFim()));
		}

		return c.list();
	}
	
	
}
