package dao;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.springframework.stereotype.Repository;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.support.ServletContextParameterFactoryBean;

import bean.BeanSelect;
import common.dao.GenericDAO;
import common.dao.IDAO;
import sicura.entities.ComboDisposizioni;

@Repository
public class GenericComboDAO extends GenericDAO<ComboDisposizioni, Integer> implements IDAO<ComboDisposizioni, Integer> {

	public List<BeanSelect> getComboValues(String tableName, String tipologia, String campo) {
		String sql = String.format("select codice, descrizione from %s where Tipologia=:tipologia And Campo=:campo ORDER BY ID",
				tableName);
		
		boolean tx = startTransaction();
		try {
			SQLQuery q = currentSession().createSQLQuery(sql);
			q.setResultTransformer(new AliasToBeanResultTransformer(BeanSelect.class));
			q
				.setParameter("tipologia", tipologia)
				.setParameter("campo", campo);		
			
			List<BeanSelect> res = q.list();
			
			return res;
			
		} finally {
			if (tx)
				tx = commit();
		}
	}	
	
	

	public  List<BeanSelect> getCausaliEsiti() {
		String sql = "SELECT causale Codice, Descrizione FROM Causali_Esiti WHERE Tipologia='AEA' And Insoluto=1";
		boolean tx = startTransaction();
		try {
			SQLQuery q = currentSession().createSQLQuery(sql);
			q.setResultTransformer(new AliasToBeanResultTransformer(BeanSelect.class));
			q
				.addScalar("Codice")
				.addScalar("Descrizione")
			;
			
			List<BeanSelect> res = q.list();
			
			return res;
			
		} finally {
			if (tx)
				tx = commit();
		}			
	}		
	
	public String getComboValue(String tableName, String tipologia, String campo, String codice) {
		String sql = String.format("select descrizione from %s where Tipologia=:tipologia And Campo=:campo and Codice=:codice",
				tableName);
		
//		boolean tx = startTransaction();
		try {
			SQLQuery q = currentSession().createSQLQuery(sql);
			q
				.setParameter("tipologia", tipologia)
				.setParameter("campo", campo)		
				.setParameter("codice",codice);
			
			String res = (String)q.uniqueResult();
			
			return res;
			
		} finally {
//			if (tx)
//				tx = commit();
		}
	}


}
