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.Calle;
import com.gfi.constants.Constants;
import com.gfi.utils.UtilSQL;
import com.gfi.utils.Utilities;

/**
 * CalleDaoImpl.
 * 
 * @author GFI
 */
@Repository()
@Transactional()
public class CalleDaoImpl implements CalleDao {

	private JdbcTemplate jdbcTemplate;

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

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

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

			return new Calle(resultSet.getString("CODPROVINCIA"), resultSet.getString("CODMUNICIPIO"),
					UtilSQL.getLong(resultSet, "CODCALLE"), UtilSQL.getLong(resultSet, "IDCALLE"),
					resultSet.getString("DESCRIPCION"), resultSet.getString("TIPOVIA"),
					resultSet.getString("TIPOVIAID"), null);
		}
	};

	/**
	 * 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 Calle table.
	 * 
	 *  calle
	 *            Pagination
	 *  Calle
	 *
	 * @param calle the calle
	 * @return the calle
	 */
	@Transactional(readOnly = true)
	public Calle find(Calle calle) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// WHERE
		List<Object> params = new ArrayList<Object>();
		if (!Utilities.isEmptyNumber(calle.getIdCalle())) {
			query.append(" WHERE t1.ID_CALLE = ? ");
			params.add(calle.getIdCalle());
		} else {
			query.append(" WHERE t1.COD_PROVINCIA = ? AND t1.COD_MUNICIPIO = ? AND t1.COD_CALLE = ? ");
			params.add(calle.getCodProvincia());
			params.add(calle.getCodMunicipio());
			params.add(calle.getCodCalle());
		}

		StringBuilder traza = new StringBuilder("[CalleDaoImpl]: find ");
		traza.append(query.toString());
		traza.append("\n Parametros: ").append(params.toArray());
		CalleDaoImpl.LOGGER.info(traza.toString());

		List<Calle> calleList = this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
		return (Calle) DataAccessUtils.uniqueResult(calleList);
	}

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(calle, true);
		if (!mapaWhere.get("query").toString().trim().isEmpty()) {
			StringBuilder where = new StringBuilder(" WHERE 1=1 ");
			where.append(mapaWhere.get("query"));
			query.append(where);
		}
		List<?> params = (List<?>) mapaWhere.get("params");

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

	/**
	 * Finds a List of rows in the Calle table.
	 * 
	 *  calle
	 *            Calle
	 *  startsWith
	 *            Boolean
	 *  List
	 *
	 * @param calle the calle
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<Calle> findAllLike(Calle calle, Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(calle, startsWith);
		if (!mapaWhere.get("query").toString().trim().isEmpty()) {
			StringBuilder where = new StringBuilder(" WHERE 1=1 ");
			where.append(mapaWhere.get("query"));
			query.append(where);
		}

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

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

	/**
	 * Counts rows in the Calle table.
	 * 
	 *  calle
	 *            Calle
	 *  Long
	 *
	 * @param calle the calle
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Calle calle) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM CALLE t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(calle, true);
		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());
	}

	/**
	 * Counts rows in the Calle table.
	 * 
	 *  calle
	 *            Calle
	 *  startsWith
	 *            Boolean
	 *  Long
	 *
	 * @param calle the calle
	 * @param startsWith the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(Calle calle, Boolean startsWith) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM CALLE t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(calle, startsWith);
		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.COD_PROVINCIA CODPROVINCIA, t1.COD_MUNICIPIO CODMUNICIPIO, t1.COD_CALLE CODCALLE, t1.ID_CALLE IDCALLE, t1.DESCRIPCION DESCRIPCION, t1.TIPO_VIA TIPOVIA, t1.TIPO_VIA_ID TIPOVIAID ");
		if (includeFrom) {
			query.append(" FROM CALLE T1 ");
		}
		return query.toString();
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Calle entity
	 * 
	 *  calle
	 *            Calle Bean with the criteria values to filter by.
	 *  startsWith
	 *            Boolean
	 *  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 calle the calle
	 * @param startsWith the starts with
	 * @return the where map
	 */
	private Map<String, ?> getWhereMap(Calle calle, Boolean startsWith) {

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

		if (calle != null) {
			if (calle.getCodCalle() != null) {
				UtilSQL.createFilterSQL(where, params, "T1.COD_CALLE", calle.getCodCalle());
			}
			if (calle.getCodProvincia() != null) {
				UtilSQL.createFilterSQL(where, params, "T1.COD_PROVINCIA", calle.getCodProvincia());
			}
			if (calle.getCodMunicipio() != null) {
				UtilSQL.createFilterSQL(where, params, "T1.COD_MUNICIPIO", calle.getCodMunicipio());
			}
			/**
			 * Para la calle filtramos las descripcion siempre con LIKE
			 */
			if (calle.getDescripcion() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "T1.DESCRIPCION", calle.getDescripcion(), startsWith);
			}
			if (calle.getIdTipoVia() != null && !Utilities.isEmpty(calle.getIdTipoVia())) {
				UtilSQL.createFilterSQL(where, params, "T1.TIPO_VIA_ID", calle.getIdTipoVia());
			}

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

		return mapWhere;
	}
}