package com.ejie.ab39a.dao;

import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;
import com.gfi.constants.Constants;
import com.gfi.utils.UtilSQL;
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.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.ab39a.model.Municipio;

/**
 * MunicipioDaoImpl.
 * 
 *  
 */

@Repository
@Transactional
public class MunicipioDaoImpl implements MunicipioDao {

	private static final String[] ORDER_BY_WHITE_LIST = new String[] { "ID_MUNICIPIO", "ID_PROVINCIA", "DESC_OF" };

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Municipio> rwMap = new RowMapper<Municipio>() {
		@Override
		public Municipio mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Municipio(resultSet.getString("IDMUNICIPIO"), resultSet.getString("IDPROVINCIA"),
					resultSet.getString("DESCOF"));
		}
	};

	private RowMapper<Municipio> rwMapPK = new RowMapper<Municipio>() {
		@Override
		public Municipio mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Municipio(resultSet.getString("IDMUNICIPIO"), resultSet.getString("IDPROVINCIA"),
					resultSet.getString("DESCOF"));
		}
	};

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

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the Municipio table.
	 *
	 * @param municipio
	 *            Municipio
	 * @return Municipio
	 */
	@Override
	public Municipio add(Municipio municipio) {
		StringBuilder query = new StringBuilder(
				"INSERT INTO MUNICIPIO (ID_MUNICIPIO, ID_PROVINCIA, DESC_OF) VALUES (?,?,?)");
		this.jdbcTemplate.update(query.toString(), municipio.getIdMunicipio(), municipio.getIdProvincia(),
				municipio.getDescOf());
		return municipio;
	}

	/**
	 * Updates a single row in the Municipio table.
	 *
	 * @param municipio
	 *            Municipio
	 * @return Municipio
	 */
	@Override
	public Municipio update(Municipio municipio) {
		StringBuilder query = new StringBuilder("UPDATE MUNICIPIO SET ");
		query.append(" WHERE ID_MUNICIPIO=? AND ID_PROVINCIA=? AND DESC_OF=?");
		this.jdbcTemplate.update(query.toString(), municipio.getIdMunicipio(), municipio.getIdProvincia(),
				municipio.getDescOf());
		return municipio;
	}

	/**
	 * Finds a single row in the Municipio table.
	 *
	 * @param municipio
	 *            Municipio
	 * @return Municipio
	 */
	@Override
	@Transactional(readOnly = true)
	public Municipio find(Municipio municipio) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
		// WHERE
		query.append(" WHERE t1.ID_MUNICIPIO = ?   AND t1.ID_PROVINCIA = ?   AND t1.DESC_OF = ?  ");

		List<Municipio> municipioList = this.jdbcTemplate.query(query.toString(), this.rwMap,
				municipio.getIdMunicipio(), municipio.getIdProvincia(), municipio.getDescOf());
		return DataAccessUtils.uniqueResult(municipioList);
	}

	/**
	 * Removes a single row in the Municipio table.
	 *
	 * @param municipio
	 *            Municipio
	 */
	@Override
	public void remove(Municipio municipio) {
		String query = "DELETE FROM MUNICIPIO WHERE ID_MUNICIPIO=? AND ID_PROVINCIA=? AND DESC_OF=?";
		this.jdbcTemplate.update(query, municipio.getIdMunicipio(), municipio.getIdProvincia(), municipio.getDescOf());
	}

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

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

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

		// if (jqGridRequestDto != null) {
		// query = JQGridManager.getPaginationQuery(jqGridRequestDto, query,
		// MunicipioDaoImpl.ORDER_BY_WHITE_LIST);
		// }

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

	/**
	 * Finds rows in the Municipio table using like.
	 * 
	 * @param municipio
	 *            Municipio
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<Municipio>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Municipio> findAllLike(Municipio municipio, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

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

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

		if (jqGridRequestDto != null) {
			query = JQGridManager.getPaginationQuery(jqGridRequestDto, query, MunicipioDaoImpl.ORDER_BY_WHITE_LIST);
		}

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Municipio table.
	 * 
	 * @param municipio
	 *            Municipio
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllCount(Municipio municipio) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM MUNICIPIO t1 ");

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

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

		return this.jdbcTemplate.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Counts rows in the Municipio table using like.
	 * 
	 * @param municipio
	 *            Municipio
	 * @param startsWith
	 *            Boolean
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllLikeCount(Municipio municipio, Boolean startsWith) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM MUNICIPIO t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(municipio, 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.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Reorder the data list of Municipio selected for rup_table
	 * 
	 * @param municipio
	 *            Municipio
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<TableRowDto<Municipio>>
	 */
	@Override
	public List<TableRowDto<Municipio>> reorderSelection(Municipio municipio, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

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

		// Parámetros de filtrado
		@SuppressWarnings(value = "unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhere.get("params");

		// SQL para la reordenación
		StringBuilder sbReorderSelectionSQL = JQGridManager.getReorderQuery(query, jqGridRequestDto, Municipio.class,
				filterParamList, "IDMUNICIPIO, IDPROVINCIA, DESCOF");

		return this.jdbcTemplate.query(sbReorderSelectionSQL.toString(),
				new RowNumResultSetExtractor<Municipio>(this.rwMapPK, jqGridRequestDto), filterParamList.toArray());
	}

	/**
	 * Remove multiple method for rup_table
	 * 
	 * @param filterMunicipio
	 *            Municipio
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 */
	@Override
	public void removeMultiple(Municipio filterMunicipio, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		/** TODO: select por clave */
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// WHERE
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterMunicipio, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		@SuppressWarnings(value = "unchecked")
		List<Object> params = (List<Object>) mapaWhere.get("params");

		StringBuilder sbRemoveMultipleSQL = JQGridManager.getRemoveMultipleQuery(jqGridRequestDto, Municipio.class,
				query, params, "IDMUNICIPIO, IDPROVINCIA, DESCOF");
		this.jdbcTemplate.update(sbRemoveMultipleSQL.toString(), params.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Devuelve la Select con todos los campos. Incluye el From si se indica.
	 * 
	 * @param includeFrom
	 *            boolean
	 * @return String
	 */
	private String getSelectFromQuery(boolean includeFrom) {
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_MUNICIPIO IDMUNICIPIO, t1.ID_PROVINCIA IDPROVINCIA, t1.DESC_OF DESCOF ");
		if (includeFrom) {
			query.append(" FROM MUNICIPIO t1 ");
		}
		return query.toString();
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Municipio entity
	 * 
	 * @param municipio
	 *            Municipio Bean with the criteria values to filter by.
	 * @return 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.
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereMap(Municipio municipio) {

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

		if (municipio != null) {
			if (municipio.getIdMunicipio() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_MUNICIPIO", municipio.getIdMunicipio());
			}
			if (municipio.getIdProvincia() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_PROVINCIA", municipio.getIdProvincia());
			}
			if (municipio.getDescOf() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESC_OF", municipio.getDescOf());
			}
		}

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

		return mapWhere;
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Municipio entity
	 * 
	 * @param municipio
	 *            Municipio Bean with the criteria values to filter by.
	 * @param startsWith
	 *            Boolean
	 * @return 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.
	 */
	private Map<String, Object> getWhereLikeMap(Municipio municipio, Boolean startsWith) {

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

		if (municipio != null) {
			if (municipio.getIdMunicipio() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_MUNICIPIO", municipio.getIdMunicipio(), startsWith);
			}
			if (municipio.getIdProvincia() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_PROVINCIA", municipio.getIdProvincia(), startsWith);
			}
			if (municipio.getDescOf() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESC_OF", municipio.getDescOf(), startsWith);
			}
		}

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

		return mapWhere;
	}
}
