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.Tarea;
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;

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

@Repository()
@Transactional()
public class TareaDaoImpl implements TareaDao {

	private static final String QUERY_SELECT = "SELECT t1.ID_TAREA_090 IDTAREA090, t1.ID_TRAMITE_090 IDTRAMITE090, t1.TASK_ID_090 TASKID090, t1.DESCRIPCION_ES_090 DESCRIPCIONES090, t1.DESCRIPCION_EU_090 DESCRIPCIONEU090, t1.ES_INICIAL_090 ESINICIAL090, t1.TIPO_090 TIPO090 FROM AB0490S00 t1 ";

	private JdbcTemplate jdbcTemplate;

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

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Tarea> rwMap = new RowMapper<Tarea>() {
		public Tarea mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Tarea(resultSet.getLong("IDTAREA090"),
					new Tramite(resultSet.getLong("IDTRAMITE090")),
					resultSet.getString("TASKID090"),
					resultSet.getString("DESCRIPCIONES090"),
					resultSet.getString("DESCRIPCIONEU090"),
					resultSet.getBoolean("ESINICIAL090"),
					resultSet.getString("TIPO090"));
		}
	};

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

	/**
	 * 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 Ab0490s00 table.
	 * 
	 *  ab0490s00
	 *            Ab0490s00
	 *  Ab0490s00
	 *
	 * @param ab0490s00 the ab 0490 s 00
	 * @return the tarea
	 */
	public Tarea add(Tarea ab0490s00) {
		String query = "INSERT INTO AB0490S00 (ID_TAREA_090, ID_TRAMITE_090, TASK_ID_090, DESCRIPCION_ES_090, DESCRIPCION_EU_090, ES_INICIAL_090, TIPO_090) VALUES (?,?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, ab0490s00.getIdTarea090(),
				ab0490s00.getTramite().getIdTramite089(),
				ab0490s00.getTaskId090(), ab0490s00.getDescripcionEs090(),
				ab0490s00.getDescripcionEu090(), ab0490s00.getEsInicial090(),
				ab0490s00.getTipo090());
		return ab0490s00;
	}

	/**
	 * Updates a single row in the Ab0490s00 table.
	 * 
	 *  ab0490s00
	 *            Ab0490s00
	 *  Ab0490s00
	 *
	 * @param ab0490s00 the ab 0490 s 00
	 * @return the tarea
	 */
	public Tarea update(Tarea ab0490s00) {
		String query = "UPDATE AB0490S00 SET ID_TRAMITE_090=?, TASK_ID_090=?, DESCRIPCION_ES_090=?, DESCRIPCION_EU_090=?, ES_INICIAL_090=?, TIPO_090=? WHERE ID_TAREA_090=?";
		this.jdbcTemplate.update(query,
				ab0490s00.getTramite().getIdTramite089(),
				ab0490s00.getTaskId090(), ab0490s00.getDescripcionEs090(),
				ab0490s00.getDescripcionEu090(), ab0490s00.getEsInicial090(),
				ab0490s00.getTipo090(), ab0490s00.getIdTarea090());
		return ab0490s00;
	}

	/**
	 * Finds a single row in the Ab0490s00 table.
	 * 
	 *  ab0490s00
	 *            Ab0490s00
	 *  Ab0490s00
	 *
	 * @param ab0490s00 the ab 0490 s 00
	 * @return the tarea
	 */
	@Transactional(readOnly = true)
	public Tarea find(Tarea ab0490s00) {
		StringBuilder query = new StringBuilder(TareaDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_090 = ? ");

		List<Tarea> ab0490s00List = this.jdbcTemplate.query(query.toString(),
				this.rwMap, ab0490s00.getIdTarea090());
		return (Tarea) DataAccessUtils.uniqueResult(ab0490s00List);
	}

	/**
	 * Removes a single row in the Ab0490s00 table.
	 * 
	 *  ab0490s00            Ab0490s00
	 *
	 * @param ab0490s00 the ab 0490 s 00
	 */
	public void remove(Tarea ab0490s00) {
		String query = "DELETE FROM AB0490S00 WHERE ID_TAREA_090=?";
		this.jdbcTemplate.update(query, ab0490s00.getIdTarea090());
	}

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

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

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0490s00 table.
	 * 
	 *  ab0490s00
	 *            Ab0490s00
	 *  Long
	 *
	 * @param ab0490s00 the ab 0490 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Tarea ab0490s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0490S00 t1 ");

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

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

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

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

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (ab0490s00 != null && ab0490s00.getIdTarea090() != null) {
			where.append(" AND t1.ID_TAREA_090 = ?");
			params.add(ab0490s00.getIdTarea090());
		}
		if (ab0490s00 != null && ab0490s00.getTramite() != null
				&& ab0490s00.getTramite().getIdTramite089() != null) {
			where.append(" AND t1.ID_TRAMITE_090 = ?");
			params.add(ab0490s00.getTramite().getIdTramite089());
		}
		if (ab0490s00 != null && ab0490s00.getTaskId090() != null) {
			where.append(" AND t1.TASK_ID_090 = ?");
			params.add(ab0490s00.getTaskId090());
		}
		if (ab0490s00 != null && ab0490s00.getDescripcionEs090() != null) {
			where.append(" AND t1.DESCRIPCION_ES_090 = ?");
			params.add(ab0490s00.getDescripcionEs090());
		}
		if (ab0490s00 != null && ab0490s00.getDescripcionEu090() != null) {
			where.append(" AND t1.DESCRIPCION_EU_090 = ?");
			params.add(ab0490s00.getDescripcionEu090());
		}
		if (ab0490s00 != null && ab0490s00.getEsInicial090() != null) {
			where.append(" AND t1.ES_INICIAL_090 = ?");
			params.add(ab0490s00.getEsInicial090());
		}
		if (ab0490s00 != null && ab0490s00.getTipo090() != null) {
			where.append(" AND t1.TIPO_090 = ?");
			params.add(ab0490s00.getTipo090());
		}

		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 Ab0490s00 entity.
	 * 
	 *  ab0490s00            Ab0490s00 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 ab0490s00 the ab 0490 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(Tarea ab0490s00,
			Boolean startsWith) {

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

		if (ab0490s00 != null && ab0490s00.getIdTarea090() != null) {
			where.append(" AND t1.ID_TAREA_090 = ?");
			params.add(ab0490s00.getIdTarea090());
		}
		if (ab0490s00 != null && ab0490s00.getTramite() != null
				&& ab0490s00.getTramite().getIdTramite089() != null) {
			where.append(" AND t1.ID_TRAMITE_090 = ?");
			params.add(ab0490s00.getTramite().getIdTramite089());
		}
		if (ab0490s00 != null && ab0490s00.getTaskId090() != null) {
			where.append(" AND UPPER(t1.TASK_ID_090) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0490s00.getTaskId090().toUpperCase() + "%");
			} else {
				params.add("%" + ab0490s00.getTaskId090().toUpperCase() + "%");
			}
			where.append(" AND t1.TASK_ID_090 IS NOT NULL");
		}
		if (ab0490s00 != null && ab0490s00.getDescripcionEs090() != null) {
			where.append(
					" AND UPPER(t1.DESCRIPCION_ES_090) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0490s00.getDescripcionEs090().toUpperCase() + "%");
			} else {
				params.add("%" + ab0490s00.getDescripcionEs090().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESCRIPCION_ES_090 IS NOT NULL");
		}
		if (ab0490s00 != null && ab0490s00.getDescripcionEu090() != null) {
			where.append(
					" AND UPPER(t1.DESCRIPCION_EU_090) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0490s00.getDescripcionEu090().toUpperCase() + "%");
			} else {
				params.add("%" + ab0490s00.getDescripcionEu090().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESCRIPCION_EU_090 IS NOT NULL");
		}
		if (ab0490s00 != null && ab0490s00.getEsInicial090() != null) {
			where.append(" AND t1.ES_INICIAL_090 = ?");
			params.add(ab0490s00.getEsInicial090());
		}
		if (ab0490s00 != null && ab0490s00.getTipo090() != null) {
			where.append(" AND t1.TIPO_090 = ?");
			params.add(ab0490s00.getTipo090());
		}

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