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

/**
 * Ab0489s00DaoImpl generated by UDA, 06-Feb-2017 12:46:17.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class TramiteDaoImpl implements TramiteDao {

	private static final String QUERY_SELECT = "SELECT t1.ID_TRAMITE_089 IDTRAMITE089, t1.PROCEDURE_ID_089 PROCEDUREID089, t1.PROCEEDING_ID_089 PROCEEDINGID089, t1.DESCRIPCION_ES_089 DESCRIPCIONES089, t1.DESCRIPCION_EU_089 DESCRIPCIONEU089 FROM AB0489S00 t1 ";

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Tramite> rwMap = new RowMapper<Tramite>() {
		public Tramite mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Tramite(resultSet.getLong("IDTRAMITE089"),
					resultSet.getString("PROCEDUREID089"),
					resultSet.getString("PROCEEDINGID089"),
					resultSet.getString("DESCRIPCIONES089"),
					resultSet.getString("DESCRIPCIONEU089"));
		}
	};

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

	/**
	 * 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 Ab0489s00 table.
	 * 
	 *  ab0489s00
	 *            Ab0489s00
	 *  Ab0489s00
	 *
	 * @param ab0489s00 the ab 0489 s 00
	 * @return the tramite
	 */
	public Tramite add(Tramite ab0489s00) {
		String query = "INSERT INTO AB0489S00 (ID_TRAMITE_089, PROCEDURE_ID_089, PROCEEDING_ID_089, DESCRIPCION_ES_089, DESCRIPCION_EU_089) VALUES (?,?,?,?,?)";
		this.jdbcTemplate.update(query, ab0489s00.getIdTramite089(),
				ab0489s00.getProcedureId089(), ab0489s00.getProceedingId089(),
				ab0489s00.getDescripcionEs089(),
				ab0489s00.getDescripcionEu089());
		return ab0489s00;
	}

	/**
	 * Updates a single row in the Ab0489s00 table.
	 * 
	 *  ab0489s00
	 *            Ab0489s00
	 *  Ab0489s00
	 *
	 * @param ab0489s00 the ab 0489 s 00
	 * @return the tramite
	 */
	public Tramite update(Tramite ab0489s00) {
		String query = "UPDATE AB0489S00 SET PROCEDURE_ID_089=?, PROCEEDING_ID_089=?, DESCRIPCION_ES_089=?, DESCRIPCION_EU_089=? WHERE ID_TRAMITE_089=?";
		this.jdbcTemplate.update(query, ab0489s00.getProcedureId089(),
				ab0489s00.getProceedingId089(), ab0489s00.getDescripcionEs089(),
				ab0489s00.getDescripcionEu089(), ab0489s00.getIdTramite089());
		return ab0489s00;
	}

	/**
	 * Finds a single row in the Ab0489s00 table.
	 * 
	 *  ab0489s00
	 *            Ab0489s00
	 *  Ab0489s00
	 *
	 * @param ab0489s00 the ab 0489 s 00
	 * @return the tramite
	 */
	@Transactional(readOnly = true)
	public Tramite find(Tramite ab0489s00) {
		StringBuilder query = new StringBuilder(TramiteDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TRAMITE_089 = ? ");

		List<Tramite> ab0489s00List = this.jdbcTemplate.query(query.toString(),
				this.rwMap, ab0489s00.getIdTramite089());
		return (Tramite) DataAccessUtils.uniqueResult(ab0489s00List);
	}

	/**
	 * Finds a single row in the Tramite table.
	 * 
	 *  proceedingId
	 *            String
	 *  procedureId
	 *            String
	 *  Tramite
	 *
	 * @param proceedingId the proceeding id
	 * @param procedureId the procedure id
	 * @return the tramite
	 */
	@Transactional(readOnly = true)
	public Tramite findByProceedingIdProcedureId(String proceedingId,
			String procedureId) {
		StringBuilder query = new StringBuilder(TramiteDaoImpl.QUERY_SELECT);
		query.append(
				" WHERE t1.PROCEEDING_ID_089 = ? AND t1.PROCEDURE_ID_089 = ? ");

		List<Tramite> tareasList = this.jdbcTemplate.query(query.toString(),
				this.rwMap, proceedingId, procedureId);
		return (Tramite) DataAccessUtils.uniqueResult(tareasList);
	}

	/**
	 * Removes a single row in the Ab0489s00 table.
	 * 
	 *  ab0489s00            Ab0489s00
	 *
	 * @param ab0489s00 the ab 0489 s 00
	 */
	public void remove(Tramite ab0489s00) {
		String query = "DELETE FROM AB0489S00 WHERE ID_TRAMITE_089=?";
		this.jdbcTemplate.update(query, ab0489s00.getIdTramite089());
	}

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

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

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0489s00 table.
	 * 
	 *  ab0489s00
	 *            Ab0489s00
	 *  Long
	 *
	 * @param ab0489s00 the ab 0489 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Tramite ab0489s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0489S00 t1 ");

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

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

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

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

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (ab0489s00 != null && ab0489s00.getIdTramite089() != null) {
			where.append(" AND t1.ID_TRAMITE_089 = ?");
			params.add(ab0489s00.getIdTramite089());
		}
		if (ab0489s00 != null && ab0489s00.getProcedureId089() != null) {
			where.append(" AND t1.PROCEDURE_ID_089 = ?");
			params.add(ab0489s00.getProcedureId089());
		}
		if (ab0489s00 != null && ab0489s00.getProceedingId089() != null) {
			where.append(" AND t1.PROCEEDING_ID_089 = ?");
			params.add(ab0489s00.getProceedingId089());
		}
		if (ab0489s00 != null && ab0489s00.getDescripcionEs089() != null) {
			where.append(" AND t1.DESCRIPCION_ES_089 = ?");
			params.add(ab0489s00.getDescripcionEs089());
		}
		if (ab0489s00 != null && ab0489s00.getDescripcionEu089() != null) {
			where.append(" AND t1.DESCRIPCION_EU_089 = ?");
			params.add(ab0489s00.getDescripcionEu089());
		}

		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 Ab0489s00 entity.
	 * 
	 *  ab0489s00            Ab0489s00 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 ab0489s00 the ab 0489 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(Tramite ab0489s00,
			Boolean startsWith) {

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

		if (ab0489s00 != null && ab0489s00.getIdTramite089() != null) {
			where.append(" AND t1.ID_TRAMITE_089 = ?");
			params.add(ab0489s00.getIdTramite089());
		}
		if (ab0489s00 != null && ab0489s00.getProcedureId089() != null) {
			where.append(" AND UPPER(t1.PROCEDURE_ID_089) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0489s00.getProcedureId089().toUpperCase() + "%");
			} else {
				params.add("%" + ab0489s00.getProcedureId089().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.PROCEDURE_ID_089 IS NOT NULL");
		}
		if (ab0489s00 != null && ab0489s00.getProceedingId089() != null) {
			where.append(
					" AND UPPER(t1.PROCEEDING_ID_089) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0489s00.getProceedingId089().toUpperCase() + "%");
			} else {
				params.add("%" + ab0489s00.getProceedingId089().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.PROCEEDING_ID_089 IS NOT NULL");
		}
		if (ab0489s00 != null && ab0489s00.getDescripcionEs089() != null) {
			where.append(
					" AND UPPER(t1.DESCRIPCION_ES_089) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0489s00.getDescripcionEs089().toUpperCase() + "%");
			} else {
				params.add("%" + ab0489s00.getDescripcionEs089().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESCRIPCION_ES_089 IS NOT NULL");
		}
		if (ab0489s00 != null && ab0489s00.getDescripcionEu089() != null) {
			where.append(
					" AND UPPER(t1.DESCRIPCION_EU_089) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0489s00.getDescripcionEu089().toUpperCase() + "%");
			} else {
				params.add("%" + ab0489s00.getDescripcionEu089().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESCRIPCION_EU_089 IS NOT NULL");
		}

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