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.OS2;
import com.ejie.ab04b.model.Tramite;
import com.ejie.ab04b.model.TramiteOS2;
import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * Ab0492s00DaoImpl generated by UDA, 05-Apr-2017 09:34:34.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class TramiteOS2DaoImpl implements TramiteOS2Dao {

	private static final String QUERY_SELECT = "SELECT t1.ID_TRAMITE_092 IDTRAMITE092, t1.TIPO_TRAMITE_092 TIPOTRAMITE092, t1.TERRIT_OS2_092 TERRITOS2092, t1.ANO_OS2_092 ANOOS2092, t1.NUM_OS2_092 NUMOS2092 FROM AB0492S00 t1 ";

	private JdbcTemplate jdbcTemplate;

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

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TramiteOS2> rwMap = new RowMapper<TramiteOS2>() {
		public TramiteOS2 mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {

			TramiteOS2 tram = new TramiteOS2(resultSet.getLong("IDTRAMITE092"),
					new Tramite(resultSet.getLong("TIPOTRAMITE092")), null);

			tram.setos2(new OS2(resultSet.getString("TERRITOS2092"),
					resultSet.getString("ANOOS2092"),
					resultSet.getInt("NUMOS2092")));

			return tram;
		}
	};

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

	/**
	 * 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 Ab0492s00 table.
	 * 
	 *  ab0492s00
	 *            Ab0492s00
	 *  Ab0492s00
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @return the tramite OS 2
	 */

	public TramiteOS2 add(TramiteOS2 ab0492s00) {
		String query = "INSERT INTO AB0492S00 (ID_TRAMITE_092, TIPO_TRAMITE_092, TERRIT_OS2_092, ANO_OS2_092, NUM_OS2_092, NUM_REGISTRO_092, FEC_REGISTRO_092) VALUES (?,?,?,?,?,?,?)";

		// Obtenemos la secuencia
		ab0492s00.setIdTramite092(
				Secuencias.TRAMITE_OS2.getNextLong(jdbcTemplate));

		this.jdbcTemplate.update(query, ab0492s00.getIdTramite092(),
				ab0492s00.getTipoTramite().getIdTramite089(),
				ab0492s00.getos2().getTeros2060(),
				ab0492s00.getos2().getAnoos2060(),
				ab0492s00.getos2().getNumos2060(),
				ab0492s00.getNumRegistro092(), ab0492s00.getFecRegistro092());
		return ab0492s00;
	}

	/**
	 * Updates a single row in the Ab0492s00 table.
	 * 
	 *  ab0492s00
	 *            Ab0492s00
	 *  Ab0492s00
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @return the tramite OS 2
	 */
	public TramiteOS2 update(TramiteOS2 ab0492s00) {
		String query = "UPDATE AB0492S00 SET TIPO_TRAMITE_092=?, TERRIT_OS2_092=?, ANO_OS2_092=?, NUM_OS2_092=? WHERE ID_TRAMITE_092=?";
		this.jdbcTemplate.update(query, ab0492s00.getTipoTramite(),
				ab0492s00.getos2().getTeros2060(),
				ab0492s00.getos2().getAnoos2060(),
				ab0492s00.getos2().getNumos2060(), ab0492s00.getIdTramite092());
		return ab0492s00;
	}

	/**
	 * Finds a single row in the Ab0492s00 table.
	 * 
	 *  ab0492s00
	 *            Ab0492s00
	 *  Ab0492s00
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @return the tramite OS 2
	 */
	@Transactional(readOnly = true)
	public TramiteOS2 find(TramiteOS2 ab0492s00) {
		StringBuilder query = new StringBuilder(TramiteOS2DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TRAMITE_092 = ? ");

		List<TramiteOS2> ab0492s00List = this.jdbcTemplate.query(
				query.toString(), this.rwMap, ab0492s00.getIdTramite092());
		return (TramiteOS2) DataAccessUtils.uniqueResult(ab0492s00List);
	}

	/**
	 * Removes a single row in the Ab0492s00 table.
	 * 
	 *  ab0492s00            Ab0492s00
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 */
	public void remove(TramiteOS2 ab0492s00) {
		String query = "DELETE FROM AB0492S00 WHERE ID_TRAMITE_092=?";
		this.jdbcTemplate.update(query, ab0492s00.getIdTramite092());
	}

	/**
	 * Finds a list of rows in the Ab0492s00 table.
	 * 
	 *  ab0492s00
	 *            Ab0492s00
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<Ab0492s00>
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TramiteOS2> findAll(TramiteOS2 ab0492s00,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(TramiteOS2DaoImpl.QUERY_SELECT);

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(ab0492s00);
		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<TramiteOS2>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

	/**
	 * Finds rows in the Ab0492s00 table using like.
	 * 
	 *  ab0492s00
	 *            Ab0492s00
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<Ab0492s00>
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TramiteOS2> findAllLike(TramiteOS2 ab0492s00,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(TramiteOS2DaoImpl.QUERY_SELECT);

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0492s00, 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<TramiteOS2>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0492s00 table.
	 * 
	 *  ab0492s00
	 *            Ab0492s00
	 *  Long
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(TramiteOS2 ab0492s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0492S00 t1 ");

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0492s00, 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 Ab0492s00 selected for rup_table.
	 * 
	 *  ab0492s00            Ab0492s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0492s00>>
	 *
	 * @param ab0492s00 the ab 0492 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TramiteOS2>> reorderSelection(TramiteOS2 ab0492s00,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(TramiteOS2DaoImpl.QUERY_SELECT);
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0492s00, 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, TramiteOS2.class, filterParamList,
				"ID_TRAMITE_092");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            Ab0492s00
	 *  searchParams            Ab0492s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0492s00>>
	 *
	 * @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<TramiteOS2>> search(TramiteOS2 filterParams,
			TramiteOS2 searchParams, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(TramiteOS2DaoImpl.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, TramiteOS2.class, filterParamList,
				searchSQL, searchParamList, from_alias, "ID_TRAMITE_092");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (ab0492s00 != null && ab0492s00.getIdTramite092() != null) {
			where.append(" AND t1.ID_TRAMITE_092 = ?");
			params.add(ab0492s00.getIdTramite092());
		}
		if (ab0492s00 != null && ab0492s00.getTipoTramite() != null) {
			where.append(" AND t1.TIPO_TRAMITE_092 = ?");
			params.add(ab0492s00.getTipoTramite());
		}
		if (ab0492s00 != null && ab0492s00.getos2() != null
				&& ab0492s00.getos2().getTeros2060() != null) {
			where.append(" AND t1.TERRIT_OS2_092 = ?");
			params.add(ab0492s00.getos2().getTeros2060());
		}
		if (ab0492s00 != null && ab0492s00.getos2() != null
				&& ab0492s00.getos2().getAnoos2060() != null) {
			where.append(" AND t1.ANO_OS2_092 = ?");
			params.add(ab0492s00.getos2().getAnoos2060());
		}
		if (ab0492s00 != null && ab0492s00.getos2() != null
				&& ab0492s00.getos2().getNumos2060() != null) {
			where.append(" AND t1.NUM_OS2_092 = ?");
			params.add(ab0492s00.getos2().getNumos2060());
		}

		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 Ab0492s00 entity.
	 * 
	 *  ab0492s00            Ab0492s00 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 ab0492s00 the ab 0492 s 00
	 * @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(TramiteOS2 ab0492s00,
			Boolean startsWith) {

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

		if (ab0492s00 != null && ab0492s00.getIdTramite092() != null) {
			where.append(" AND t1.ID_TRAMITE_092 = ?");
			params.add(ab0492s00.getIdTramite092());
		}
		if (ab0492s00 != null && ab0492s00.getTipoTramite() != null) {
			where.append(" AND t1.TIPO_TRAMITE_092 = ?");
			params.add(ab0492s00.getTipoTramite());
		}
		if (ab0492s00 != null && ab0492s00.getos2() != null
				&& ab0492s00.getos2().getTeros2060() != null) {
			where.append(" AND t1.TERRIT_OS2_092 = ?");
			params.add(ab0492s00.getos2().getTeros2060());
		}
		if (ab0492s00 != null && ab0492s00.getos2() != null
				&& ab0492s00.getos2().getAnoos2060() != null) {
			where.append(" AND t1.ANO_OS2_092 = ?");
			params.add(ab0492s00.getos2().getAnoos2060());
		}
		if (ab0492s00 != null && ab0492s00.getos2() != null
				&& ab0492s00.getos2().getNumos2060() != null) {
			where.append(" AND t1.NUM_OS2_092 = ?");
			params.add(ab0492s00.getos2().getNumos2060());
		}

		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;
}
