package br.com.senac.dao;

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

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import br.com.senac.model.Pojo;

public abstract class DAOSpringJdbc<T extends Pojo> implements DAO<T> {
	protected JdbcTemplate template;

	private final class EntityMapper implements RowMapper {
		public T mapRow(ResultSet rs, int rowNum) throws SQLException {
			return buildEntity(rs);
		}
	}
	
	abstract protected String buildQueryFindById();
	abstract protected String buildQueryFindAll();
	abstract protected T buildEntity(ResultSet rs);

	public DAOSpringJdbc(DataSource dataSource) {
		this.template = new JdbcTemplate(dataSource);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return this.template.query(buildQueryFindAll(), new EntityMapper());
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(String query) {
		return (List<T>)this.template.query(query, new EntityMapper());
	}

	@SuppressWarnings("unchecked")
	public T findById(int id) {
		return (T)this.template.queryForObject(buildQueryFindById(), 
				new Object[] {new Integer(id)},
				new EntityMapper());
	}
}
