package com.ejie.ab04b.dao;

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.ab04b.constantes.Secuencias;
import com.ejie.ab04b.model.ComunicacionApertura;
import com.ejie.ab04b.model.Tramite;
import com.ejie.ab04b.model.TramiteAperturas;
import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * TramiteAperturasDaoImpl generated by UDA, 02-Feb-2017 13:49:16.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class TramiteAperturasDaoImpl implements TramiteAperturasDao {

	private static final String QUERY_SELECT = "SELECT t1.ID_TRAMITE_062 IDTRAMITE062, t1.TIPO_TRAMITE_062 TIPOTRAMITE062, t1.TERRIT_APERTURA_062 TERRITAPERTURA062, t1.ANO_APERTURA_062 ANOAPERTURA062, t1.NUM_APERTURA_062 NUMAPERTURA062 FROM AB0462S00 t1 ";

	private JdbcTemplate jdbcTemplate;

	/**
	 * Gets the jdbc template.
	 * 
	 *  JdbcTemplate
	 *
	 * @return the jdbc template
	 */
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TramiteAperturas> rwMap = new RowMapper<TramiteAperturas>() {
		public TramiteAperturas mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			TramiteAperturas tram = new TramiteAperturas(
					resultSet.getLong("IDTRAMITE062"),
					new Tramite(resultSet.getLong("TIPOTRAMITE062")), null);

			tram.setApertura(new ComunicacionApertura(
					resultSet.getString("TERRITAPERTURA062"),
					resultSet.getString("ANOAPERTURA062"),
					resultSet.getLong("NUMAPERTURA062")));

			return tram;
		}
	};

	private RowMapper<TramiteAperturas> rwMapPK = new RowMapper<TramiteAperturas>() {
		public TramiteAperturas mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new TramiteAperturas(resultSet.getLong("IDTRAMITE062"));
		}
	};

	/**
	 * 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);
	}

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the TramiteAperturas table.
	 * 
	 *  tramiteAperturas
	 *            TramiteAperturas
	 *  TramiteAperturas
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @return the tramite aperturas
	 */
	public TramiteAperturas add(TramiteAperturas tramiteAperturas) {
		String query = "INSERT INTO AB0462S00 (ID_TRAMITE_062, TIPO_TRAMITE_062, TERRIT_APERTURA_062, ANO_APERTURA_062, NUM_APERTURA_062, NUM_REGISTRO_062, FEC_REGISTRO_062) VALUES (?,?,?,?,?,?,?)";

		// Obtenemos la secuencia
		tramiteAperturas.setIdTramite062(
				Secuencias.TRAMITE_APERTURAS.getNextLong(jdbcTemplate));

		this.jdbcTemplate.update(query, tramiteAperturas.getIdTramite062(),
				tramiteAperturas.getTipoTramite().getIdTramite089(),
				tramiteAperturas.getApertura().getTerape056(),
				tramiteAperturas.getApertura().getAnoape056(),
				tramiteAperturas.getApertura().getNumape056(),
				tramiteAperturas.getNumRegistro062(),
				tramiteAperturas.getFecRegistro062());
		return tramiteAperturas;
	}

	/**
	 * Updates a single row in the TramiteAperturas table.
	 * 
	 *  tramiteAperturas
	 *            TramiteAperturas
	 *  TramiteAperturas
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @return the tramite aperturas
	 */
	public TramiteAperturas update(TramiteAperturas tramiteAperturas) {
		String query = "UPDATE AB0462S00 SET TIPO_TRAMITE_062=?, TERRIT_APERTURA_062=?, ANO_APERTURA_062=?, NUM_APERTURA_062=? WHERE ID_TRAMITE_062=?";
		this.jdbcTemplate.update(query,
				tramiteAperturas.getTipoTramite().getIdTramite089(),
				tramiteAperturas.getApertura().getTerape056(),
				tramiteAperturas.getApertura().getAnoape056(),
				tramiteAperturas.getApertura().getNumape056(),
				tramiteAperturas.getIdTramite062());
		return tramiteAperturas;
	}

	/**
	 * Finds a single row in the TramiteAperturas table.
	 * 
	 *  tramiteAperturas
	 *            TramiteAperturas
	 *  TramiteAperturas
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @return the tramite aperturas
	 */
	@Transactional(readOnly = true)
	public TramiteAperturas find(TramiteAperturas tramiteAperturas) {
		StringBuilder query = new StringBuilder(
				TramiteAperturasDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TRAMITE_062 = ? ");

		List<TramiteAperturas> tramiteAperturasList = this.jdbcTemplate.query(
				query.toString(), this.rwMap,
				tramiteAperturas.getIdTramite062());
		return (TramiteAperturas) DataAccessUtils
				.uniqueResult(tramiteAperturasList);
	}

	/**
	 * Removes a single row in the TramiteAperturas table.
	 * 
	 *  tramiteAperturas            TramiteAperturas
	 *
	 * @param tramiteAperturas the tramite aperturas
	 */
	public void remove(TramiteAperturas tramiteAperturas) {
		String query = "DELETE FROM AB0462S00 WHERE ID_TRAMITE_062=?";
		this.jdbcTemplate.update(query, tramiteAperturas.getIdTramite062());
	}

	/**
	 * Finds a list of rows in the TramiteAperturas table.
	 * 
	 *  tramiteAperturas
	 *            TramiteAperturas
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<TramiteAperturas>
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TramiteAperturas> findAll(TramiteAperturas tramiteAperturas,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(
				TramiteAperturasDaoImpl.QUERY_SELECT);

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

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

	/**
	 * Finds rows in the TramiteAperturas table using like.
	 * 
	 *  tramiteAperturas
	 *            TramiteAperturas
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<TramiteAperturas>
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TramiteAperturas> findAllLike(TramiteAperturas tramiteAperturas,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				TramiteAperturasDaoImpl.QUERY_SELECT);

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(tramiteAperturas);
		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 TramiteAperturas table using like.
	 * 
	 *  tramiteAperturas
	 *            TramiteAperturas
	 *  startsWith
	 *            Boolean
	 *  Long
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @param startsWith the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(TramiteAperturas tramiteAperturas,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0462S00 t1 ");

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

	/**
	 * Reorder the data list of TramiteAperturas selected for rup_table.
	 * 
	 *  tramiteAperturas            TramiteAperturas
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TramiteAperturas>>
	 *
	 * @param tramiteAperturas the tramite aperturas
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TramiteAperturas>> reorderSelection(
			TramiteAperturas tramiteAperturas,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				TramiteAperturasDaoImpl.QUERY_SELECT);
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tramiteAperturas,
				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, TramiteAperturas.class,
				filterParamList, "ID_TRAMITE_062");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            TramiteAperturas
	 *  searchParams            TramiteAperturas
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TramiteAperturas>>
	 *
	 * @param filterParams the filter params
	 * @param searchParams the search params
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TramiteAperturas>> search(
			TramiteAperturas filterParams, TramiteAperturas searchParams,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				TramiteAperturasDaoImpl.QUERY_SELECT);
		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");

		// FILTRADO
		Map<String, ?> mapaWhereFilter = this.getWhereLikeMap(filterParams,
				startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhereFilter.get("query"));
		query.append(where);
		// Filter params
		@SuppressWarnings(value = "unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhereFilter
				.get("params");

		// BUSQUEDA
		Map<String, Object> mapaWhereSearch = this.getWhereLikeMap(searchParams,
				startsWith);
		String searchSQL = ((StringBuilder) mapaWhereSearch.get("query"))
				.toString();
		// Search params
		@SuppressWarnings(value = "unchecked")
		List<Object> searchParamList = (List<Object>) mapaWhereSearch
				.get("params");

		// SQL
		StringBuilder sbReorderSelectionSQL = JQGridManager.getSearchQuery(
				query, jqGridRequestDto, TramiteAperturas.class,
				filterParamList, searchSQL, searchParamList, from_alias,
				"ID_TRAMITE_062");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (tramiteAperturas != null
				&& tramiteAperturas.getIdTramite062() != null) {
			where.append(" AND t1.ID_TRAMITE_062 = ?");
			params.add(tramiteAperturas.getIdTramite062());
		}
		if (tramiteAperturas != null
				&& tramiteAperturas.getTipoTramite() != null && tramiteAperturas
						.getTipoTramite().getIdTramite089() != null) {
			where.append(" AND t1.TIPO_TRAMITE_062 = ?");
			params.add(tramiteAperturas.getTipoTramite().getIdTramite089());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getTerape056() != null) {
			where.append(" AND t1.TERRIT_APERTURA_062 = ?");
			params.add(tramiteAperturas.getApertura().getTerape056());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getAnoape056() != null) {
			where.append(" AND t1.ANO_APERTURA_062 = ?");
			params.add(tramiteAperturas.getApertura().getAnoape056());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getNumape056() != null) {
			where.append(" AND t1.NUM_APERTURA_062 = ?");
			params.add(tramiteAperturas.getApertura().getNumape056());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getNumExpDesde() != null) {
			where.append(" AND t1.NUM_APERTURA_062 >= ?");
			params.add(tramiteAperturas.getApertura().getNumExpDesde());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getNumExpHasta() != null) {
			where.append(" AND t1.NUM_APERTURA_062 <= ?");
			params.add(tramiteAperturas.getApertura().getNumExpHasta());
		}

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

		return mapWhere;
	}

	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the TramiteAperturas entity.
	 * 
	 *  tramiteAperturas            TramiteAperturas 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 tramiteAperturas the tramite aperturas
	 * @param startsWith the starts with
	 * @return the where like map
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, Object> getWhereLikeMap(
			TramiteAperturas tramiteAperturas, Boolean startsWith) {

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

		if (tramiteAperturas != null
				&& tramiteAperturas.getIdTramite062() != null) {
			where.append(" AND t1.ID_TRAMITE_062 = ?");
			params.add(tramiteAperturas.getIdTramite062());
		}
		if (tramiteAperturas != null
				&& tramiteAperturas.getTipoTramite() != null && tramiteAperturas
						.getTipoTramite().getIdTramite089() != null) {
			where.append(" AND t1.TIPO_TRAMITE_062 = ?");
			params.add(tramiteAperturas.getTipoTramite().getIdTramite089());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getTerape056() != null) {
			where.append(" AND t1.TERRIT_APERTURA_062 = ?");
			params.add(tramiteAperturas.getApertura().getTerape056());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getAnoape056() != null) {
			where.append(" AND t1.ANO_APERTURA_062 = ?");
			params.add(tramiteAperturas.getApertura().getAnoape056());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getNumape056() != null) {
			where.append(" AND t1.NUM_APERTURA_062 = ?");
			params.add(tramiteAperturas.getApertura().getNumape056());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getNumExpDesde() != null) {
			where.append(" AND t1.NUM_APERTURA_062 >= ?");
			params.add(tramiteAperturas.getApertura().getNumExpDesde());
		}
		if (tramiteAperturas != null && tramiteAperturas.getApertura() != null
				&& tramiteAperturas.getApertura().getNumExpHasta() != null) {
			where.append(" AND t1.NUM_APERTURA_062 <= ?");
			params.add(tramiteAperturas.getApertura().getNumExpHasta());
		}

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

		return mapWhere;
	}

	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

	/**
	 * StringBuilder initilization value
	 */
	public static final int STRING_BUILDER_INIT = 4096;
}
