package com.rjconsultores.ventaboletos.dao.hibernate;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.stereotype.Repository;

import com.rjconsultores.ventaboletos.dao.FlywayUtilDAO;
import com.rjconsultores.ventaboletos.entidad.EsquemaAgrupacion;

@Repository("flywayUtilDAO")
public class FlywayUtilHibernateDAO extends GenericHibernateDAO<EsquemaAgrupacion, Integer> implements FlywayUtilDAO {

	private static Logger log = LogManager.getLogger(FlywayUtilHibernateDAO.class);

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

	@Override
	public boolean existeErroExecucaoScript() {
		final List<Boolean> ls = new ArrayList<Boolean>();

		try {

			getSession().doWork(new Work() {

				@Override
				public void execute(Connection conn) throws SQLException {
					ResultSet rs = conn.prepareStatement("select count(*) from \"schema_version\" where \"success\"=0").executeQuery();
					if (rs.next()) {
						ls.add(rs.getInt(1) > 0);
					}
					
					rs.close();
				}
			});

		} catch (DataAccessResourceFailureException e) {
			log.error("", e);
		} catch (HibernateException e) {
			log.error("", e);
		} catch (IllegalStateException e) {
			log.error("", e);
		} 

		return (ls.size()>0 && ls.get(0));

	}

}
