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.TipoDocumento;
import com.ejie.ab04b.util.Utilities;
import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * Ab0491s00DaoImpl generated by UDA, 15-Feb-2017 11:33:53.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class TipoDocumentoDaoImpl implements TipoDocumentoDao {

	private static final String QUERY_SELECT = "SELECT t1.ID_TIPO_DOC_091 IDTIPODOC091, t1.DESCRIPCION_ES_091 DESCRIPCIONES091, t1.DESCRIPCION_EU_091 DESCRIPCIONEU091, t1.TIPO_DOKUSI_091 TIPODOKUSI091, t1.ASUNTO_DOKUSI_091 ASUNTODOKUSI091, t1.APORT_GEN_091 APORTGEN091 FROM AB0491S00 t1 ";

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TipoDocumento> rwMap = new RowMapper<TipoDocumento>() {
		public TipoDocumento mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new TipoDocumento(resultSet.getLong("IDTIPODOC091"),
					resultSet.getString("DESCRIPCIONES091"),
					resultSet.getString("DESCRIPCIONEU091"),
					resultSet.getString("TIPODOKUSI091"),
					resultSet.getString("ASUNTODOKUSI091"),
					resultSet.getString("APORTGEN091"));
		}
	};

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

	/**
	 * 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 Ab0491s00 table.
	 * 
	 *  ab0491s00
	 *            Ab0491s00
	 *  Ab0491s00
	 *
	 * @param ab0491s00 the ab 0491 s 00
	 * @return the tipo documento
	 */
	public TipoDocumento add(TipoDocumento ab0491s00) {
		String query = "INSERT INTO AB0491S00 (ID_TIPO_DOC_091, DESCRIPCION_ES_091, DESCRIPCION_EU_091, TIPO_DOKUSI_091, ASUNTO_DOKUSI_091, APORT_GEN_091) VALUES (?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, ab0491s00.getIdTipoDoc091(),
				ab0491s00.getDescripcionEs091(),
				ab0491s00.getDescripcionEu091(), ab0491s00.getTipoDokusi091(),
				ab0491s00.getAsuntoDokusi091(), ab0491s00.getAportGen091());
		return ab0491s00;
	}

	/**
	 * Updates a single row in the Ab0491s00 table.
	 * 
	 *  ab0491s00
	 *            Ab0491s00
	 *  Ab0491s00
	 *
	 * @param ab0491s00 the ab 0491 s 00
	 * @return the tipo documento
	 */
	public TipoDocumento update(TipoDocumento ab0491s00) {
		String query = "UPDATE AB0491S00 SET DESCRIPCION_ES_091=?, DESCRIPCION_EU_091=?, TIPO_DOKUSI_091=?, ASUNTO_DOKUSI_091=?, APORT_GEN_091=? WHERE ID_TIPO_DOC_091=?";
		this.jdbcTemplate.update(query, ab0491s00.getDescripcionEs091(),
				ab0491s00.getDescripcionEu091(), ab0491s00.getTipoDokusi091(),
				ab0491s00.getAsuntoDokusi091(), ab0491s00.getAportGen091(),
				ab0491s00.getIdTipoDoc091());
		return ab0491s00;
	}

	/**
	 * Finds a single row in the Ab0491s00 table.
	 * 
	 *  ab0491s00
	 *            Ab0491s00
	 *  Ab0491s00
	 *
	 * @param ab0491s00 the ab 0491 s 00
	 * @return the tipo documento
	 */
	@Transactional(readOnly = true)
	public TipoDocumento find(TipoDocumento ab0491s00) {
		StringBuilder query = new StringBuilder(
				TipoDocumentoDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TIPO_DOC_091 = ? ");

		List<TipoDocumento> ab0491s00List = this.jdbcTemplate.query(
				query.toString(), this.rwMap, ab0491s00.getIdTipoDoc091());
		return (TipoDocumento) DataAccessUtils.uniqueResult(ab0491s00List);
	}

	/**
	 * Finds a single row in the Ab0491s00 table.
	 * 
	 *  ab0491s00
	 *            Ab0491s00
	 *  Ab0491s00
	 *
	 * @param ab0491s00 the ab 0491 s 00
	 * @return the tipo documento
	 */
	@Transactional(readOnly = true)
	public TipoDocumento findByTipoAsuntoDocumental(TipoDocumento ab0491s00) {
		StringBuilder query = new StringBuilder(
				TipoDocumentoDaoImpl.QUERY_SELECT);
		query.append(" WHERE 1=1 ");
		List<Object> params = new ArrayList<Object>();
		if (!Utilities.getInstance().isEmpty(ab0491s00.getTipoDokusi091())) {
			query.append(" AND t1.TIPO_DOKUSI_091 = ? ");
			params.add(ab0491s00.getTipoDokusi091());
		}
		if (!Utilities.getInstance().isEmpty(ab0491s00.getAsuntoDokusi091())) {
			query.append(" AND t1.ASUNTO_DOKUSI_091 = ? ");
			params.add(ab0491s00.getAsuntoDokusi091());
		}

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

	/**
	 * Removes a single row in the Ab0491s00 table.
	 * 
	 *  ab0491s00            Ab0491s00
	 *
	 * @param ab0491s00 the ab 0491 s 00
	 */
	public void remove(TipoDocumento ab0491s00) {
		String query = "DELETE FROM AB0491S00 WHERE ID_TIPO_DOC_091=?";
		this.jdbcTemplate.update(query, ab0491s00.getIdTipoDoc091());
	}

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

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

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0491s00 table.
	 * 
	 *  ab0491s00
	 *            Ab0491s00
	 *  Long
	 *
	 * @param ab0491s00 the ab 0491 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(TipoDocumento ab0491s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0491S00 t1 ");

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

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

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

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

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (ab0491s00 != null && ab0491s00.getIdTipoDoc091() != null) {
			where.append(" AND t1.ID_TIPO_DOC_091 = ?");
			params.add(ab0491s00.getIdTipoDoc091());
		}
		if (ab0491s00 != null && ab0491s00.getDescripcionEs091() != null) {
			where.append(" AND t1.DESCRIPCION_ES_091 = ?");
			params.add(ab0491s00.getDescripcionEs091());
		}
		if (ab0491s00 != null && ab0491s00.getDescripcionEu091() != null) {
			where.append(" AND t1.DESCRIPCION_EU_091 = ?");
			params.add(ab0491s00.getDescripcionEu091());
		}
		if (ab0491s00 != null && ab0491s00.getTipoDokusi091() != null) {
			where.append(" AND t1.TIPO_DOKUSI_091 = ?");
			params.add(ab0491s00.getTipoDokusi091());
		}
		if (ab0491s00 != null && ab0491s00.getAsuntoDokusi091() != null) {
			where.append(" AND t1.ASUNTO_DOKUSI_091 = ?");
			params.add(ab0491s00.getAsuntoDokusi091());
		}
		if (ab0491s00 != null && ab0491s00.getAportGen091() != null) {
			where.append(" AND t1.APORT_GEN_091 = ?");
			params.add(ab0491s00.getAportGen091());
		}

		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 Ab0491s00 entity.
	 * 
	 *  ab0491s00            Ab0491s00 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 ab0491s00 the ab 0491 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(TipoDocumento ab0491s00,
			Boolean startsWith) {

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

		if (ab0491s00 != null && ab0491s00.getIdTipoDoc091() != null) {
			where.append(" AND t1.ID_TIPO_DOC_091 = ?");
			params.add(ab0491s00.getIdTipoDoc091());
		}
		if (ab0491s00 != null && ab0491s00.getDescripcionEs091() != null) {
			where.append(
					" AND UPPER(t1.DESCRIPCION_ES_091) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0491s00.getDescripcionEs091().toUpperCase() + "%");
			} else {
				params.add("%" + ab0491s00.getDescripcionEs091().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESCRIPCION_ES_091 IS NOT NULL");
		}
		if (ab0491s00 != null && ab0491s00.getDescripcionEu091() != null) {
			where.append(
					" AND UPPER(t1.DESCRIPCION_EU_091) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0491s00.getDescripcionEu091().toUpperCase() + "%");
			} else {
				params.add("%" + ab0491s00.getDescripcionEu091().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESCRIPCION_EU_091 IS NOT NULL");
		}
		if (ab0491s00 != null && ab0491s00.getTipoDokusi091() != null) {
			where.append(" AND UPPER(t1.TIPO_DOKUSI_091) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0491s00.getTipoDokusi091().toUpperCase() + "%");
			} else {
				params.add(
						"%" + ab0491s00.getTipoDokusi091().toUpperCase() + "%");
			}
			where.append(" AND t1.TIPO_DOKUSI_091 IS NOT NULL");
		}
		if (ab0491s00 != null && ab0491s00.getAsuntoDokusi091() != null) {
			where.append(
					" AND UPPER(t1.ASUNTO_DOKUSI_091) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0491s00.getAsuntoDokusi091().toUpperCase() + "%");
			} else {
				params.add("%" + ab0491s00.getAsuntoDokusi091().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.ASUNTO_DOKUSI_091 IS NOT NULL");
		}
		if (ab0491s00 != null && ab0491s00.getAportGen091() != null) {
			where.append(" AND t1.APORT_GEN_091 = ?");
			params.add(ab0491s00.getAportGen091());
		}

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