package com.ejie.ab04b.dao.nora;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ejie.ab04b.model.nora.Provincia;
import com.gfi.constants.Constants;
import com.gfi.utils.UtilSQL;

/**
 * ProvinciaDaoImpl.
 * 
 * @author GFI
 */
@Repository()
@Transactional()
public class ProvinciaDaoImpl implements ProvinciaDao {

	private JdbcTemplate jdbcTemplate;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ProvinciaDaoImpl.class);

	private RowMapper<Provincia> rwMap = new RowMapper<Provincia>() {

		public Provincia mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {

			return new Provincia(resultSet.getString("CODPROVINCIA"),
					resultSet.getString("DESCRIPCION"),
					resultSet.getString("CODAUTONOMIA"));
		}
	};

	/**
	 * Method use to set the datasource.
	 * 
	 *  dataSource
	 *            DataSource
	 *
	 * @param dataSource the new data source
	 */
	@Resource()
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	/**
	 * Finds a single row in the Provincia table.
	 * 
	 *  provincia
	 *            Pagination
	 *  Provincia
	 *
	 * @param provincia the provincia
	 * @return the provincia
	 */
	@Transactional(readOnly = true)
	public Provincia find(Provincia provincia) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// WHERE
		query.append(" WHERE T1.ID = ? ");

		StringBuilder traza = new StringBuilder("[ProvinciaDaoImpl]: find ");
		traza.append(query.toString());
		traza.append("\n Parametros: ").append(provincia.getCodProvincia());
		ProvinciaDaoImpl.LOGGER.info(traza.toString());

		List<Provincia> provinciaList = this.jdbcTemplate.query(
				query.toString(), this.rwMap, provincia.getCodProvincia());
		return (Provincia) DataAccessUtils.uniqueResult(provinciaList);
	}

	/**
	 * Finds a List of rows in the Provincia table.
	 * 
	 *  provincia
	 *            Provincia
	 *  List
	 *
	 * @param provincia the provincia
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<Provincia> findAll(Provincia provincia) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(provincia);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		List<?> params = (List<?>) mapaWhere.get("params");

		return (List<Provincia>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

	/**
	 * Counts rows in the Provincia table.
	 * 
	 *  provincia
	 *            Provincia
	 *  Long
	 *
	 * @param provincia the provincia
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Provincia provincia) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM PROVINCIA T1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(provincia);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		List<?> params = (List<?>) mapaWhere.get("params");

		return this.jdbcTemplate.queryForLong(query.toString(),
				params.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Devuelve la Select con todos los campos. Incluye el From si se indica.
	 * 
	 *  includeFrom
	 *            boolean
	 *  String
	 *
	 * @param includeFrom the include from
	 * @return the select from query
	 */
	private String getSelectFromQuery(boolean includeFrom) {
		StringBuilder query = new StringBuilder(
				"SELECT T1.ID CODPROVINCIA, T1.DS_O DESCRIPCION, T1.AUTONOMIA_ID CODAUTONOMIA ");
		if (includeFrom) {
			query.append(" FROM PROVINCIA T1 ");
		}
		return query.toString();
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Provincia entity
	 * 
	 *  provincia
	 *            Provincia Bean with the criteria values to filter by.
	 *  Map created with two keys key query stores the sql query syntax
	 *         key params stores the parameter values to be used in the
	 *         condition sentence.
	 *
	 * @param provincia the provincia
	 * @return the where map
	 */
	private Map<String, ?> getWhereMap(Provincia provincia) {

		StringBuilder where = new StringBuilder(Constants.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (provincia != null) {
			if (provincia.getCodAutonomia() != null) {
				UtilSQL.createFilterSQL(where, params, "T1.AUTONOMIA_ID",
						provincia.getCodAutonomia());
			}
			if (provincia.getCodProvincia() != null) {
				UtilSQL.createFilterSQL(where, params, "T1.ID",
						provincia.getCodProvincia());
			}
			if (provincia.getDescripcion() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "T1.DS_O",
						provincia.getDescripcion(), false);
			}
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}

	/**
	 * Finds a List of rows in the Provincia table.
	 * 
	 *  provincia
	 *            Provincia
	 *  List
	 *
	 * @param provincia the provincia
	 * @return the provincia
	 */
	@Transactional(readOnly = true)
	public Provincia findAllFirst(Provincia provincia) {
		StringBuilder query = new StringBuilder(
				"SELECT T1.ID CODPROVINCIA, T1.DS_O DESCRIPCION, T1.AUTONOMIA_ID CODAUTONOMIA   FROM PROVINCIA T1 WHERE "
						+ " UPPER(translate(T1.DS_O, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%'||UPPER(translate(?, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU'))||'%' and rownum=1 ");

		query.append(" ORDER BY T1.DS_O");

		List<Provincia> provinciaList = this.jdbcTemplate.query(
				query.toString(), this.rwMap, provincia.getDescripcion());

		return (Provincia) DataAccessUtils.uniqueResult(provinciaList);
	}

}