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

/**
 * Ab0475s00DaoImpl generated by UDA, 27-jun-2017 11:01:08.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class NumeracionExpedienteDaoImpl implements NumeracionExpedienteDao {
	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<NumeracionExpediente> rwMap = new RowMapper<NumeracionExpediente>() {
		public NumeracionExpediente mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new NumeracionExpediente(resultSet.getString("TIPEXP075"),
					resultSet.getString("TEREXP075"),
					resultSet.getString("ANOEXP075"),
					resultSet.getInt("NUMEXP075"));
		}
	};

	private RowMapper<NumeracionExpediente> rwMapPK = new RowMapper<NumeracionExpediente>() {
		public NumeracionExpediente mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new NumeracionExpediente(resultSet.getString("TIPEXP075"),
					resultSet.getString("TEREXP075"),
					resultSet.getString("ANOEXP075"),
					resultSet.getInt("NUMEXP075"));
		}
	};

	/**
	 * 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 Ab0475s00 table.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  Ab0475s00
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @return the numeracion expediente
	 */
	public NumeracionExpediente add(NumeracionExpediente ab0475s00) {
		String query = "INSERT INTO AB0475S00 (TIPEXP_075, TEREXP_075, ANOEXP_075, NUMEXP_075) VALUES (?,?,?,?)";
		this.jdbcTemplate.update(query, ab0475s00.getTipexp075(),
				ab0475s00.getTerexp075(), ab0475s00.getAnoexp075(),
				ab0475s00.getNumexp075());
		return ab0475s00;
	}

	/**
	 * Updates a single row in the Ab0475s00 table.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  Ab0475s00
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @return the numeracion expediente
	 */
	public NumeracionExpediente update(NumeracionExpediente ab0475s00) {
		String query = "UPDATE AB0475S00 SET  WHERE TIPEXP_075=? AND TEREXP_075=? AND ANOEXP_075=? AND NUMEXP_075=?";
		this.jdbcTemplate.update(query, ab0475s00.getTipexp075(),
				ab0475s00.getTerexp075(), ab0475s00.getAnoexp075(),
				ab0475s00.getNumexp075());
		return ab0475s00;
	}

	/**
	 * Obtiene el siguiente numape.
	 * 
	 *  numeracion            NumeracionExpediente
	 *  Long Long
	 *
	 * @param numeracion the numeracion
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long obtenerNumExpSiguiente(NumeracionExpediente numeracion) {

		StringBuilder query = new StringBuilder(
				"SELECT NVL(MAX(NUMEXP_075) + 1, 1) FROM AB0475S00  where ANOEXP_075= ? AND TEREXP_075 = ? AND TIPEXP_075 = ?");
		return this.jdbcTemplate.queryForObject(query.toString(), Long.class,
				numeracion.getAnoexp075(), numeracion.getTerexp075(),
				numeracion.getTipexp075());
	}

	/**
	 * Actualiza el siguiente numape.
	 * 
	 *  numeracion            NumeracionExpediente
	 *
	 * @param numeracion the numeracion
	 */
	@Transactional(readOnly = true)
	public void actualizarNumExpSiguiente(NumeracionExpediente numeracion) {

		StringBuilder query = new StringBuilder(
				"UPDATE AB0475S00 SET NUMEXP_075 = NUMEXP_075 + 1  where ANOEXP_075= ? AND TEREXP_075 = ? AND TIPEXP_075 = ?");
		int numactualizdas = this.jdbcTemplate.update(query.toString(),
				numeracion.getAnoexp075(), numeracion.getTerexp075(),
				numeracion.getTipexp075());

		if (numactualizdas == 0) {
			numeracion.setNumexp075(1);
			this.add(numeracion);
		}
	}

	/**
	 * Finds a single row in the Ab0475s00 table.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  Ab0475s00
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @return the numeracion expediente
	 */
	@Transactional(readOnly = true)
	public NumeracionExpediente find(NumeracionExpediente ab0475s00) {
		String query = "SELECT t1.TIPEXP_075 TIPEXP075, t1.TEREXP_075 TEREXP075, t1.ANOEXP_075 ANOEXP075, t1.NUMEXP_075 NUMEXP075 FROM AB0475S00 t1  WHERE t1.TIPEXP_075 = ?   AND t1.TEREXP_075 = ?   AND t1.ANOEXP_075 = ?   AND t1.NUMEXP_075 = ?  ";

		List<NumeracionExpediente> ab0475s00List = this.jdbcTemplate.query(
				query, this.rwMap, ab0475s00.getTipexp075(),
				ab0475s00.getTerexp075(), ab0475s00.getAnoexp075(),
				ab0475s00.getNumexp075());
		return (NumeracionExpediente) DataAccessUtils
				.uniqueResult(ab0475s00List);
	}

	/**
	 * Removes a single row in the Ab0475s00 table.
	 * 
	 *  ab0475s00            Ab0475s00
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 */
	public void remove(NumeracionExpediente ab0475s00) {
		String query = "DELETE FROM AB0475S00 WHERE TIPEXP_075=? AND TEREXP_075=? AND ANOEXP_075=? AND NUMEXP_075=?";
		this.jdbcTemplate.update(query, ab0475s00.getTipexp075(),
				ab0475s00.getTerexp075(), ab0475s00.getAnoexp075(),
				ab0475s00.getNumexp075());
	}

	/**
	 * Finds a list of rows in the Ab0475s00 table.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<Ab0475s00>
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<NumeracionExpediente> findAll(NumeracionExpediente ab0475s00,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.TIPEXP_075 TIPEXP075,t1.TEREXP_075 TEREXP075,t1.ANOEXP_075 ANOEXP075,t1.NUMEXP_075 NUMEXP075 ");
		query.append("FROM AB0475S00 t1 ");

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

	/**
	 * Finds rows in the Ab0475s00 table using like.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<Ab0475s00>
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<NumeracionExpediente> findAllLike(
			NumeracionExpediente ab0475s00, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.TIPEXP_075 TIPEXP075,t1.TEREXP_075 TEREXP075,t1.ANOEXP_075 ANOEXP075,t1.NUMEXP_075 NUMEXP075 ");
		query.append("FROM AB0475S00 t1 ");

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0475s00 table.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  Long
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(NumeracionExpediente ab0475s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0475S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(ab0475s00);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		List<?> params = (List<?>) mapaWhere.get("params");

		return this.jdbcTemplate.queryForObject(query.toString(), Long.class,
				params.toArray());
	}

	/**
	 * Counts rows in the Ab0475s00 table using like.
	 * 
	 *  ab0475s00
	 *            Ab0475s00
	 *  startsWith
	 *            Boolean
	 *  Long
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @param startsWith the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(NumeracionExpediente ab0475s00,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0475S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0475s00, 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.queryForObject(query.toString(), Long.class,
				params.toArray());
	}

	/**
	 * Reorder the data list of Ab0475s00 selected for rup_table.
	 * 
	 *  ab0475s00            Ab0475s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0475s00>>
	 *
	 * @param ab0475s00 the ab 0475 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override
	public List<TableRowDto<NumeracionExpediente>> reorderSelection(
			NumeracionExpediente ab0475s00, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.TIPEXP_075 TIPEXP075,t1.TEREXP_075 TEREXP075,t1.ANOEXP_075 ANOEXP075,t1.NUMEXP_075 NUMEXP075 ");
		// FROM
		query.append("FROM AB0475S00 t1 ");
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0475s00, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		// Parámetros de filtrado
		@SuppressWarnings("unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhere.get("params");

		// SQL para la reordenación
		StringBuilder sbReorderSelectionSQL = JQGridManager.getReorderQuery(
				query, jqGridRequestDto, NumeracionExpediente.class,
				filterParamList, "TIPEXP_075,TEREXP_075,ANOEXP_075,NUMEXP_075");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            Ab0475s00
	 *  searchParams            Ab0475s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0475s00>>
	 *
	 * @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<NumeracionExpediente>> search(
			NumeracionExpediente filterParams,
			NumeracionExpediente searchParams,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.TIPEXP_075 TIPEXP075,t1.TEREXP_075 TEREXP075,t1.ANOEXP_075 ANOEXP075,t1.NUMEXP_075 NUMEXP075 ");
		// FROM
		query.append("FROM AB0475S00 t1 ");
		// 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("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("unchecked")
		List<Object> searchParamList = (List<Object>) mapaWhereSearch
				.get("params");

		// SQL
		StringBuilder sbReorderSelectionSQL = JQGridManager.getSearchQuery(
				query, jqGridRequestDto, NumeracionExpediente.class,
				filterParamList, searchSQL, searchParamList, from_alias,
				"TIPEXP_075,TEREXP_075,ANOEXP_075,NUMEXP_075");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (ab0475s00 != null && ab0475s00.getTipexp075() != null) {
			where.append(" AND t1.TIPEXP_075 = ?");
			params.add(ab0475s00.getTipexp075());
		}
		if (ab0475s00 != null && ab0475s00.getTerexp075() != null) {
			where.append(" AND t1.TEREXP_075 = ?");
			params.add(ab0475s00.getTerexp075());
		}
		if (ab0475s00 != null && ab0475s00.getAnoexp075() != null) {
			where.append(" AND t1.ANOEXP_075 = ?");
			params.add(ab0475s00.getAnoexp075());
		}
		if (ab0475s00 != null && ab0475s00.getNumexp075() != null) {
			where.append(" AND t1.NUMEXP_075 = ?");
			params.add(ab0475s00.getNumexp075());
		}

		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 Ab0475s00 entity.
	 * 
	 *  ab0475s00            Ab0475s00 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 ab0475s00 the ab 0475 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(NumeracionExpediente ab0475s00,
			Boolean startsWith) {

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

		if (ab0475s00 != null && ab0475s00.getTipexp075() != null) {
			where.append(" AND UPPER(t1.TIPEXP_075) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0475s00.getTipexp075().toUpperCase() + "%");
			} else {
				params.add("%" + ab0475s00.getTipexp075().toUpperCase() + "%");
			}
			where.append(" AND t1.TIPEXP_075 IS NOT NULL");
		}
		if (ab0475s00 != null && ab0475s00.getTerexp075() != null) {
			where.append(" AND UPPER(t1.TEREXP_075) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0475s00.getTerexp075().toUpperCase() + "%");
			} else {
				params.add("%" + ab0475s00.getTerexp075().toUpperCase() + "%");
			}
			where.append(" AND t1.TEREXP_075 IS NOT NULL");
		}
		if (ab0475s00 != null && ab0475s00.getAnoexp075() != null) {
			where.append(" AND UPPER(t1.ANOEXP_075) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0475s00.getAnoexp075().toUpperCase() + "%");
			} else {
				params.add("%" + ab0475s00.getAnoexp075().toUpperCase() + "%");
			}
			where.append(" AND t1.ANOEXP_075 IS NOT NULL");
		}
		if (ab0475s00 != null && ab0475s00.getNumexp075() != null) {
			where.append(" AND t1.NUMEXP_075 = ?");
			params.add(ab0475s00.getNumexp075());
		}

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