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

/**
 * Ab0468s00DaoImpl generated by UDA, 21-Feb-2017 12:47:21.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class DatosAvisoDaoImpl implements DatosAvisoDao {

	private static final String QUERY_SELECT = "SELECT t1.ID_DATO_AVISO_068 IDDATOAVISO068, t1.TIPO_068 TIPO068, t1.VALOR_068 VALOR068, t1.COD_DATOS_NOTIF_068 CODDATOSNOTIF068 FROM AB0468S00 t1 ";

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<DatosAviso> rwMap = new RowMapper<DatosAviso>() {
		public DatosAviso mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new DatosAviso(resultSet.getLong("IDDATOAVISO068"),
					resultSet.getInt("TIPO068"),
					resultSet.getString("VALOR068"), new DatosNotificacion(
							resultSet.getInt("CODDATOSNOTIF068")));
		}
	};

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

	/**
	 * 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 Ab0468s00 table.
	 * 
	 *  ab0468s00
	 *            Ab0468s00
	 *  Ab0468s00
	 *
	 * @param ab0468s00 the ab 0468 s 00
	 * @return the datos aviso
	 */
	public DatosAviso add(DatosAviso ab0468s00) {
		String query = "INSERT INTO AB0468S00 (ID_DATO_AVISO_068, COD_DATOS_NOTIF_068, TIPO_068, VALOR_068) VALUES (?,?,?,?)";

		ab0468s00.setIdDatoAviso068(
				Secuencias.DATOS_AVISO.getNextLong(jdbcTemplate));

		Object getAb0466s00CodDatosNotif066Aux = null;
		if (ab0468s00.getDatosNotificacion() != null && ab0468s00
				.getDatosNotificacion().getCodDatosNotif066() != null) {
			getAb0466s00CodDatosNotif066Aux = ab0468s00.getDatosNotificacion()
					.getCodDatosNotif066();
		}

		this.jdbcTemplate.update(query, ab0468s00.getIdDatoAviso068(),
				getAb0466s00CodDatosNotif066Aux, ab0468s00.getTipo068(),
				ab0468s00.getValor068());
		return ab0468s00;
	}

	/**
	 * Updates a single row in the Ab0468s00 table.
	 * 
	 *  ab0468s00
	 *            Ab0468s00
	 *  Ab0468s00
	 *
	 * @param ab0468s00 the ab 0468 s 00
	 * @return the datos aviso
	 */
	public DatosAviso update(DatosAviso ab0468s00) {
		String query = "UPDATE AB0468S00 SET COD_DATOS_NOTIF_068=?, TIPO_068=?, VALOR_068=? WHERE ID_DATO_AVISO_068=?";
		Object getAb0466s00CodDatosNotif066Aux = null;
		if (ab0468s00.getDatosNotificacion() != null && ab0468s00
				.getDatosNotificacion().getCodDatosNotif066() != null) {
			getAb0466s00CodDatosNotif066Aux = ab0468s00.getDatosNotificacion()
					.getCodDatosNotif066();
		}
		this.jdbcTemplate.update(query, getAb0466s00CodDatosNotif066Aux,
				ab0468s00.getTipo068(), ab0468s00.getValor068(),
				ab0468s00.getIdDatoAviso068());
		return ab0468s00;
	}

	/**
	 * Finds a single row in the Ab0468s00 table.
	 * 
	 *  ab0468s00
	 *            Ab0468s00
	 *  Ab0468s00
	 *
	 * @param ab0468s00 the ab 0468 s 00
	 * @return the datos aviso
	 */
	@Transactional(readOnly = true)
	public DatosAviso find(DatosAviso ab0468s00) {
		StringBuilder query = new StringBuilder(DatosAvisoDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_DATO_AVISO_068 = ? ");

		List<DatosAviso> ab0468s00List = this.jdbcTemplate.query(
				query.toString(), this.rwMap, ab0468s00.getIdDatoAviso068());
		return (DatosAviso) DataAccessUtils.uniqueResult(ab0468s00List);
	}

	/**
	 * Removes a single row in the Ab0468s00 table.
	 * 
	 *  ab0468s00            Ab0468s00
	 *
	 * @param ab0468s00 the ab 0468 s 00
	 */
	public void remove(DatosAviso ab0468s00) {
		String query = "DELETE FROM AB0468S00 WHERE ID_DATO_AVISO_068=?";
		this.jdbcTemplate.update(query, ab0468s00.getIdDatoAviso068());
	}

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

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

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0468s00 table.
	 * 
	 *  ab0468s00
	 *            Ab0468s00
	 *  Long
	 *
	 * @param ab0468s00 the ab 0468 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(DatosAviso ab0468s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0468S00 t1 ");

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

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

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            Ab0468s00
	 *  searchParams            Ab0468s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0468s00>>
	 *
	 * @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<DatosAviso>> search(DatosAviso filterParams,
			DatosAviso searchParams, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(DatosAvisoDaoImpl.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 AND t1.COD_DATOS_NOTIF_068= t2.COD_DATOS_NOTIF_066(+) ");
		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, DatosAviso.class, filterParamList,
				searchSQL, searchParamList, from_alias, "ID_DATO_AVISO_068");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (ab0468s00 != null && ab0468s00.getIdDatoAviso068() != null) {
			where.append(" AND t1.ID_DATO_AVISO_068 = ?");
			params.add(ab0468s00.getIdDatoAviso068());
		}
		if (ab0468s00 != null && ab0468s00.getDatosNotificacion() != null
				&& ab0468s00.getDatosNotificacion()
						.getCodDatosNotif066() != null) {
			where.append(" AND t1.COD_DATOS_NOTIF_068 = ?");
			params.add(ab0468s00.getDatosNotificacion().getCodDatosNotif066());
		}
		if (ab0468s00 != null && ab0468s00.getTipo068() != null) {
			where.append(" AND t1.TIPO_068 = ?");
			params.add(ab0468s00.getTipo068());
		}
		if (ab0468s00 != null && ab0468s00.getValor068() != null) {
			where.append(" AND t1.VALOR_068 = ?");
			params.add(ab0468s00.getValor068());
		}

		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 Ab0468s00 entity.
	 * 
	 *  ab0468s00            Ab0468s00 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 ab0468s00 the ab 0468 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(DatosAviso ab0468s00,
			Boolean startsWith) {

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

		if (ab0468s00 != null && ab0468s00.getIdDatoAviso068() != null) {
			where.append(" AND t1.ID_DATO_AVISO_068 = ?");
			params.add(ab0468s00.getIdDatoAviso068());
		}
		if (ab0468s00 != null && ab0468s00.getDatosNotificacion() != null
				&& ab0468s00.getDatosNotificacion()
						.getCodDatosNotif066() != null) {
			where.append(" AND t1.COD_DATOS_NOTIF_068 = ?");
			params.add(ab0468s00.getDatosNotificacion().getCodDatosNotif066());
		}
		if (ab0468s00 != null && ab0468s00.getTipo068() != null) {
			where.append(" AND t1.TIPO_068 = ?");
			params.add(ab0468s00.getTipo068());
		}
		if (ab0468s00 != null && ab0468s00.getValor068() != null) {
			where.append(" AND UPPER(t1.VALOR_068) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0468s00.getValor068().toUpperCase() + "%");
			} else {
				params.add("%" + ab0468s00.getValor068().toUpperCase() + "%");
			}
			where.append(" AND t1.VALOR_068 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;
}
