/*
* Copyright 2021 E.J.I.E., S.A.
*
* Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);
* Solo podrá usarse esta obra si se respeta la Licencia.
* Puede obtenerse una copia de la Licencia en
*
* http://ec.europa.eu/idabc/eupl.html
*
* Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,
* el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,
* SIN GARANT�?AS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.
* Véase la Licencia en el idioma concreto que rige los permisos y limitaciones
* que establece la Licencia.
*/
package com.ejie.ad74a.dao;

import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.TableManager;
import com.ejie.x38.dto.TableRequestDto;
import com.ejie.x38.dto.TableRowDto;
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.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ejie.ad74a.model.ConvivientesInfSoci;

/**
 * ConvivientesInfSociDaoImpl generated by UDA, 07-sep-2023 11:42:25.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class ConvivientesInfSociDaoImpl implements ConvivientesInfSociDao {

	/**
	 * StringBuilder initilization value
	 */
	public static final int STRING_BUILDER_INIT = 4096;

	protected static final String[] ORDER_BY_WHITE_LIST = new String[] { "IDCONVIVIENTE82", "IDINFSOCIAL82",
			"NOMBREAPELLIDOS82", "PARENTESCO82", "FNACIMIENTO82" };

	private JdbcTemplate jdbcTemplate;

	public static final String SEQ_CONVIVIENTES_INF_SOCI = "SEQ_CONVIVIENTES_INF_SOCI";

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<ConvivientesInfSoci> rwMap = new RowMapper<ConvivientesInfSoci>() {
		public ConvivientesInfSoci mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			ConvivientesInfSoci conviviente = new ConvivientesInfSoci(resultSet.getLong("IDCONVIVIENTE82"),
					resultSet.getLong("IDINFSOCIAL82"), resultSet.getString("NOMBREAPELLIDOS82"),
					resultSet.getString("PARENTESCO82"), resultSet.getDate("FNACIMIENTO82"));

			return conviviente;
		}
	};

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

	/**
	 * Method use to set the datasource.
	 *
	 * @param dataSource DataSource
	 *
	 * @return
	 */
	@Resource
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the ConvivientesInfSoci table.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 *
	 * @return ConvivientesInfSoci
	 */
	public ConvivientesInfSoci add(ConvivientesInfSoci convivientesinfsoci) {

		GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();

		String query = "INSERT INTO CONVIVIENTES_INF_SOCI (ID_CONVIVIENTE_82, ID_INF_SOCIAL_82, NOMBRE_APELLIDOS_82, PARENTESCO_82, F_NACIMIENTO_82) "
				+ "VALUES (" + SEQ_CONVIVIENTES_INF_SOCI + ".NEXTVAL,:idInfSocial,:nombre,:parentesco,:fNacimiento)";

		MapSqlParameterSource parameters = new MapSqlParameterSource()
				.addValue("idInfSocial", convivientesinfsoci.getIdInfSocial82())
				.addValue("nombre", convivientesinfsoci.getNombreApellidos82())
				.addValue("parentesco", convivientesinfsoci.getParentesco82())
				.addValue("fNacimiento", convivientesinfsoci.getfNacimiento82());

		NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
		namedParameterJdbcTemplate.update(query, parameters, generatedKeyHolder, new String[] { "ID_CONVIVIENTE_82" });
		convivientesinfsoci.setIdConviviente82(generatedKeyHolder.getKey().longValue());

		return convivientesinfsoci;
	}

	/**
	 * Updates a single row in the ConvivientesInfSoci table.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 *
	 * @return ConvivientesInfSoci
	 */
	public ConvivientesInfSoci update(ConvivientesInfSoci convivientesinfsoci) {
		String query = "UPDATE CONVIVIENTES_INF_SOCI SET ID_INF_SOCIAL_82=?, NOMBRE_APELLIDOS_82=?, PARENTESCO_82=?, F_NACIMIENTO_82=? WHERE ID_CONVIVIENTE_82=?";
		this.jdbcTemplate.update(query, convivientesinfsoci.getIdInfSocial82(),
				convivientesinfsoci.getNombreApellidos82(), convivientesinfsoci.getParentesco82(),
				convivientesinfsoci.getfNacimiento82(), convivientesinfsoci.getIdConviviente82());
		return convivientesinfsoci;
	}

	/**
	 * Finds a single row in the ConvivientesInfSoci table.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 *
	 * @return ConvivientesInfSoci
	 */
	@Transactional(readOnly = true)
	public ConvivientesInfSoci find(ConvivientesInfSoci convivientesinfsoci) {
		String query = "SELECT t1.ID_CONVIVIENTE_82 IDCONVIVIENTE82, t1.ID_INF_SOCIAL_82 IDINFSOCIAL82, t1.NOMBRE_APELLIDOS_82 NOMBREAPELLIDOS82, t1.PARENTESCO_82 PARENTESCO82, t1.F_NACIMIENTO_82 FNACIMIENTO82 FROM CONVIVIENTES_INF_SOCI t1  WHERE t1.ID_CONVIVIENTE_82 = ?  ";

		List<ConvivientesInfSoci> convivientesinfsociList = this.jdbcTemplate.query(query, this.rwMap,
				convivientesinfsoci.getIdConviviente82());
		return DataAccessUtils.uniqueResult(convivientesinfsociList);
	}

	/**
	 * Removes a single row in the ConvivientesInfSoci table.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 */
	public void remove(ConvivientesInfSoci convivientesinfsoci) {
		String query = "DELETE FROM CONVIVIENTES_INF_SOCI WHERE ID_CONVIVIENTE_82=?";
		this.jdbcTemplate.update(query, convivientesinfsoci.getIdConviviente82());
	}

	public List<ConvivientesInfSoci> getMultiple(ConvivientesInfSoci filterConvivientesInfSoci,
			TableRequestDto tableRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_CONVIVIENTE_82 IDCONVIVIENTE82, t1.ID_INF_SOCIAL_82 IDINFSOCIAL82, t1.NOMBRE_APELLIDOS_82 NOMBREAPELLIDOS82, t1.PARENTESCO_82 PARENTESCO82, t1.F_NACIMIENTO_82 FNACIMIENTO82 ");
		// FROM
		query.append("FROM CONVIVIENTES_INF_SOCI t1 ");
		// WHERE clause & Params
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterConvivientesInfSoci, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		@SuppressWarnings("unchecked")
		List<Object> params = (List<Object>) mapaWhere.get("params");

		StringBuilder sbMultipleSQL = query.append(TableManager.getSelectMultipleQuery(tableRequestDto,
				ConvivientesInfSoci.class, params, "id_conviviente_82"));

		return this.jdbcTemplate.query(sbMultipleSQL.toString(), this.rwMap, params.toArray());
	}

	/**
	 * Finds a list of rows in the ConvivientesInfSoci table.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 * @param tableRequestDto     TableRequestDto
	 *
	 * @return List<ConvivientesInfSoci>
	 */
	@Transactional(readOnly = true)
	public List<ConvivientesInfSoci> findAll(ConvivientesInfSoci convivientesinfsoci, TableRequestDto tableRequestDto) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_CONVIVIENTE_82 IDCONVIVIENTE82,t1.ID_INF_SOCIAL_82 IDINFSOCIAL82,t1.NOMBRE_APELLIDOS_82 NOMBREAPELLIDOS82,t1.PARENTESCO_82 PARENTESCO82,t1.F_NACIMIENTO_82 FNACIMIENTO82 ");

		// FROM
		query.append("FROM CONVIVIENTES_INF_SOCI t1 ");

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

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

		if (tableRequestDto != null) {
			query = TableManager.getPaginationQuery(tableRequestDto, query,
					ConvivientesInfSociDaoImpl.ORDER_BY_WHITE_LIST);
		}

		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/**
	 * Finds rows in the ConvivientesInfSoci table using like.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 * @param tableRequestDto     TableRequestDto
	 * @param startsWith          Boolean
	 *
	 * @return List<ConvivientesInfSoci>
	 */
	@Transactional(readOnly = true)
	public List<ConvivientesInfSoci> findAllLike(ConvivientesInfSoci convivientesinfsoci,
			TableRequestDto tableRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_CONVIVIENTE_82 IDCONVIVIENTE82,t1.ID_INF_SOCIAL_82 IDINFSOCIAL82,t1.NOMBRE_APELLIDOS_82 NOMBREAPELLIDOS82,t1.PARENTESCO_82 PARENTESCO82,t1.F_NACIMIENTO_82 FNACIMIENTO82 ");

		// FROM
		query.append("FROM CONVIVIENTES_INF_SOCI t1 ");

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

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

		if (tableRequestDto != null) {
			query = TableManager.getPaginationQuery(tableRequestDto, query,
					ConvivientesInfSociDaoImpl.ORDER_BY_WHITE_LIST);
		}

		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the ConvivientesInfSoci table.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 *
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(ConvivientesInfSoci convivientesinfsoci) {
		// SELECT
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM CONVIVIENTES_INF_SOCI t1 ");

		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(convivientesinfsoci);
		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(), params.toArray(), Long.class);
	}

	/**
	 * Counts rows in the ConvivientesInfSoci table using like.
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 * @param startsWith          Boolean
	 *
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(ConvivientesInfSoci convivientesinfsoci, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM CONVIVIENTES_INF_SOCI t1 ");

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

	/**
	 * Reorder the data list of ConvivientesInfSoci selected for rup_table
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci
	 * @param tableRequestDto     TableRequestDto
	 * @param startsWith          Boolean
	 *
	 * @return List<TableRowDto<ConvivientesInfSoci>>
	 */
	@Override
	public List<TableRowDto<ConvivientesInfSoci>> reorderSelection(ConvivientesInfSoci convivientesinfsoci,
			TableRequestDto tableRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_CONVIVIENTE_82 IDCONVIVIENTE82,t1.ID_INF_SOCIAL_82 IDINFSOCIAL82,t1.NOMBRE_APELLIDOS_82 NOMBREAPELLIDOS82,t1.PARENTESCO_82 PARENTESCO82,t1.F_NACIMIENTO_82 FNACIMIENTO82 ");
		// FROM
		query.append("FROM CONVIVIENTES_INF_SOCI t1 ");
		// FILTRADO
		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(convivientesinfsoci, 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 = TableManager.getReorderQuery(query, tableRequestDto,
				ConvivientesInfSoci.class, filterParamList, "idconviviente82");

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

	/**
	 * Search method for rup_table
	 *
	 * @param filterParams    ConvivientesInfSoci
	 * @param searchParams    ConvivientesInfSoci
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 *
	 * @return List<TableRowDto<ConvivientesInfSoci>>
	 */
	@Override
	public List<TableRowDto<ConvivientesInfSoci>> search(ConvivientesInfSoci filterParams,
			ConvivientesInfSoci searchParams, TableRequestDto tableRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_CONVIVIENTE_82 IDCONVIVIENTE82,t1.ID_INF_SOCIAL_82 IDINFSOCIAL82,t1.NOMBRE_APELLIDOS_82 NOMBREAPELLIDOS82,t1.PARENTESCO_82 PARENTESCO82,t1.F_NACIMIENTO_82 FNACIMIENTO82 ");
		// FROM
		query.append("FROM CONVIVIENTES_INF_SOCI 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 = TableManager.getSearchQuery(query, tableRequestDto,
				ConvivientesInfSoci.class, filterParamList, searchSQL, searchParamList, from_alias, "IDCONVIVIENTE82");

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

	/**
	 * Remove multiple method for rup_table
	 *
	 * @param tableRequestDto TableRequestDto
	 */
	@Override
	public void removeMultiple(TableRequestDto tableRequestDto) {
		StringBuilder sbRemoveMultipleSQL = TableManager.getRemoveMultipleQuery(null, tableRequestDto,
				ConvivientesInfSoci.class, "CONVIVIENTES_INF_SOCI", "t1", new String[] { "IDCONVIVIENTE82" });

		List<String> params = tableRequestDto.getMultiselection().getSelectedIds();

		this.jdbcTemplate.update(sbRemoveMultipleSQL.toString(), params.toArray());
	}

	/*
	 * MÃ‰TODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * ConvivientesInfSoci entity
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci Bean with the criteria values
	 *                            to filter by.
	 *
	 * @return 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.
	 */
	private Map<String, ?> getWhereMap(ConvivientesInfSoci convivientesinfsoci) {
		StringBuilder where = new StringBuilder(ConvivientesInfSociDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (convivientesinfsoci != null && convivientesinfsoci.getIdConviviente82() != null) {
			where.append(" AND t1.ID_CONVIVIENTE_82 = ?");
			params.add(convivientesinfsoci.getIdConviviente82());
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getIdInfSocial82() != null) {
			where.append(" AND t1.ID_INF_SOCIAL_82 = ?");
			params.add(convivientesinfsoci.getIdInfSocial82());
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getNombreApellidos82() != null) {
			where.append(" AND t1.NOMBRE_APELLIDOS_82 = ?");
			params.add(convivientesinfsoci.getNombreApellidos82());
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getParentesco82() != null) {
			where.append(" AND t1.PARENTESCO_82 = ?");
			params.add(convivientesinfsoci.getParentesco82());
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getfNacimiento82() != null) {
			where.append(" AND t1.F_NACIMIENTO_82 = ?");
			params.add(convivientesinfsoci.getfNacimiento82());
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * ConvivientesInfSoci entity
	 *
	 * @param convivientesinfsoci ConvivientesInfSoci Bean with the criteria values
	 *                            to filter by.
	 * @param startsWith          Boolean
	 *
	 * @return 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.
	 */
	private Map<String, Object> getWhereLikeMap(ConvivientesInfSoci convivientesinfsoci, Boolean startsWith) {
		StringBuilder where = new StringBuilder(ConvivientesInfSociDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (convivientesinfsoci != null && convivientesinfsoci.getIdConviviente82() != null) {
			where.append(" AND t1.ID_CONVIVIENTE_82 = ?");
			params.add(convivientesinfsoci.getIdConviviente82());
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getIdInfSocial82() != null) {
			where.append(" AND t1.ID_INF_SOCIAL_82 = ?");
			params.add(convivientesinfsoci.getIdInfSocial82());
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getNombreApellidos82() != null) {
			where.append(" AND UPPER(t1.NOMBRE_APELLIDOS_82) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(convivientesinfsoci.getNombreApellidos82().toUpperCase() + "%");
			} else {
				params.add("%" + convivientesinfsoci.getNombreApellidos82().toUpperCase() + "%");
			}
			where.append(" AND t1.NOMBRE_APELLIDOS_82 IS NOT NULL");
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getParentesco82() != null) {
			where.append(" AND UPPER(t1.PARENTESCO_82) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(convivientesinfsoci.getParentesco82().toUpperCase() + "%");
			} else {
				params.add("%" + convivientesinfsoci.getParentesco82().toUpperCase() + "%");
			}
			where.append(" AND t1.PARENTESCO_82 IS NOT NULL");
		}
		if (convivientesinfsoci != null && convivientesinfsoci.getfNacimiento82() != null) {
			where.append(" AND t1.F_NACIMIENTO_82 = ?");
			params.add(convivientesinfsoci.getfNacimiento82());
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}
}
