package com.ejie.m62fb.dao.registroVPP;

import java.math.BigDecimal;
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.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
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.m62fb.utils.constants.IberErrorsMsgConstants;
import com.ejie.m62fb.utils.error.UFException;
import com.ejie.m62fb.dao.ComboP28Dao;
import com.ejie.m62fb.dao.PersonaDao;
import com.ejie.m62fb.dao.SQLGenericas;
import com.ejie.m62fb.dao.registroVPP.plsql.M62FuncionesPLSQL;
import com.ejie.m62fb.model.ContratoAlquilerElemento;
import com.ejie.m62fb.model.InquilinoElemento;
import com.ejie.m62fb.model.persona.Persona;
import com.ejie.m62fb.utils.sql.BDUtils;
import com.ejie.m62fb.utils.sql.UtilsResulSet;
import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * InquilinoElementoDaoImpl generated by UDA, 17-dic-2015 12:17:46.
 * 
XXXX
 */

@Repository
@Transactional
public class InquilinoElementoDaoImpl implements InquilinoElementoDao {

	@Autowired
	@SuppressWarnings("rawtypes")
	ComboP28Dao comboP28Dao;

	@Autowired
	PersonaDao personaDao;

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private final RowMapper<InquilinoElemento> rwMap = new RowMapper<InquilinoElemento>() {
		@Override
		public InquilinoElemento mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			InquilinoElemento inquilinoElemento = new InquilinoElemento();

			// Id InquilinoElemento
			inquilinoElemento.setIdInquilino(resultSet
					.getBigDecimal("IDINQUILINO"));

			// Id Contrato Alquiler
			inquilinoElemento
					.setContratoAlquilerElemento(new ContratoAlquilerElemento());
			inquilinoElemento.getContratoAlquilerElemento()
					.setIdContratoAlquiler(
							UtilsResulSet.getBigDecimal(resultSet,
									"IDCONTRATOALQ"));

			// Persona
			Persona persona = new Persona(resultSet.getBigDecimal("IDPERSONA"));
			persona.setCodigoId(resultSet.getString("NIFTITULAR"));
			persona.setNombre(resultSet.getString("NOMNOMBRE"));
			persona.setApellido1(resultSet.getString("NOMAPELLIDO1"));
			persona.setApellido2(resultSet.getString("NOMAPELLIDO2"));
			// Direccion de la persona
			persona.setDireccion(UtilsResulSet.getDireccionCompleta(resultSet,
					null));
			inquilinoElemento.setPersona(persona);

			// Indicador Vivienda Adaptada
			inquilinoElemento.setIndVivAdaptada(UtilsResulSet.getIndicadorSN(
					resultSet, "INDVIVADAPTADA"));

			// AbstractClass
			UtilsResulSet.getAbstractClass(resultSet, inquilinoElemento,
					InquilinoElementoDaoSql.ALIAS_INQUILINOELEM);

			return inquilinoElemento;
		}
	};

	private final RowMapper<InquilinoElemento> rwMapPK = new RowMapper<InquilinoElemento>() {
		@Override
		public InquilinoElemento mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new InquilinoElemento(resultSet.getBigDecimal("IDINQUILINO"));
		}
	};

	/**
	 * 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 InquilinoElemento table.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @return InquilinoElemento
	 */
	@Override
	public InquilinoElemento add(InquilinoElemento inquilinoElemento) {
		String query = InquilinoElementoDaoSql.SQL_INSERT;

		// Campos para la generación del titular
		// Id Contrato Alquiler
		BigDecimal getIdContratoAlqAux = null;
		if (inquilinoElemento.getContratoAlquilerElemento() != null
				&& inquilinoElemento.getContratoAlquilerElemento()
						.getIdContratoAlquiler() != null) {
			getIdContratoAlqAux = inquilinoElemento
					.getContratoAlquilerElemento().getIdContratoAlquiler();
		}
		// Id Persona
		BigDecimal getIdPersona = null;
		if (inquilinoElemento.getPersona() != null
				&& inquilinoElemento.getPersona().getIdPersona() != null) {
			getIdPersona = inquilinoElemento.getPersona().getIdPersona();
		}

		// Preparar Parametros
		List<Object> params = new ArrayList<Object>();
		// Id Inquilino Elemento
		params.add(inquilinoElemento.getIdInquilino());
		// Id Contrato Alquiler
		params.add(getIdContratoAlqAux);
		// Id Persona
		params.add(getIdPersona);
		// Indicador Vivienda Adaptada
		params.add(BDUtils.formatIndicadorToBD(inquilinoElemento
				.getIndVivAdaptada()));

		// CodUsuario
		SQLGenericas.getParamsAbstractClass(params, inquilinoElemento);

		this.jdbcTemplate.update(query, params.toArray());
		return inquilinoElemento;
	}

	/**
	 * Updates a single row in the InquilinoElemento table.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @return InquilinoElemento
	 */
	@Override
	public InquilinoElemento update(InquilinoElemento inquilinoElemento) {
		String query = InquilinoElementoDaoSql.SQL_UPDATE;

		// Campos para la generación del titular
		// Id Contrato Alquiler
		BigDecimal getIdContratoAlqAux = null;
		if (inquilinoElemento.getContratoAlquilerElemento() != null
				&& inquilinoElemento.getContratoAlquilerElemento()
						.getIdContratoAlquiler() != null) {
			getIdContratoAlqAux = inquilinoElemento
					.getContratoAlquilerElemento().getIdContratoAlquiler();
		}
		// Id Persona
		BigDecimal getIdPersona = null;
		if (inquilinoElemento.getPersona() != null
				&& inquilinoElemento.getPersona().getIdPersona() != null) {
			getIdPersona = inquilinoElemento.getPersona().getIdPersona();
		}

		// Preparar Parametros
		List<Object> params = new ArrayList<Object>();
		// Id Contrato Alquiler
		params.add(getIdContratoAlqAux);
		// Id Persona
		params.add(getIdPersona);
		// Indicador Vivienda Adaptada
		params.add(BDUtils.formatIndicadorToBD(inquilinoElemento
				.getIndVivAdaptada()));
		// CodUsuario
		SQLGenericas.getParamsAbstractClass(params, inquilinoElemento);

		// Campos WHERE
		// Id Inquilino Elemento
		params.add(inquilinoElemento.getIdInquilino());

		this.jdbcTemplate.update(query, params.toArray());
		return inquilinoElemento;
	}

	/**
	 * Finds a single row in the InquilinoElemento table.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @return InquilinoElemento
	 */
	@Override
	@Transactional(readOnly = true)
	public InquilinoElemento find(InquilinoElemento inquilinoElemento) {
		String query = InquilinoElementoDaoSql.SQL_FIND;

		List<InquilinoElemento> inquilinoElementoList = this.jdbcTemplate
				.query(query, this.rwMap, inquilinoElemento.getIdInquilino());
		return DataAccessUtils.uniqueResult(inquilinoElementoList);
	}

	/**
	 * FindForUpdate
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @return InquilinoElemento
	 */
	@Override
	public InquilinoElemento findForUpdate(InquilinoElemento inquilinoElemento) {
		InquilinoElemento inquilinoElementoBD;
		try {
			inquilinoElementoBD = this.jdbcTemplate.queryForObject(
					InquilinoElementoDaoSql.SQL_FIND_FOR_UPDATE, this.rwMap,
					inquilinoElemento.getIdInquilino(),
					inquilinoElemento.getFecHorUltimaModif());
		} catch (EmptyResultDataAccessException e) {
			throw new UFException(IberErrorsMsgConstants.CONCURRENCY_MSG);
		}
		if (inquilinoElementoBD == null) {
			throw new UFException(IberErrorsMsgConstants.CONCURRENCY_MSG);
		}
		return inquilinoElementoBD;
	}

	/**
	 * Removes a single row in the InquilinoElemento table.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @return
	 */
	@Override
	public void remove(InquilinoElemento inquilinoElemento) {
		/*****
		 * Llamada a function que implementa llamada a plsql
		 ****/
		M62FuncionesPLSQL m62FuncionesPLSQL = new M62FuncionesPLSQL(
				this.jdbcTemplate.getDataSource());
		m62FuncionesPLSQL.borrarInquilinoContratoElemento(inquilinoElemento
				.getIdInquilino());
	}

	/**
	 * Finds a list of rows in the InquilinoElemento table.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<InquilinoElemento>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<InquilinoElemento> findAll(InquilinoElemento inquilinoElemento,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(
				InquilinoElementoDaoSql.SQL_FIND_ALL);

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

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

		if (jqGridRequestDto != null) {
			query = JQGridManager.getPaginationQuery(jqGridRequestDto, query);
		}

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

	/**
	 * Finds rows in the InquilinoElemento table using like.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<InquilinoElemento>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<InquilinoElemento> findAllLike(
			InquilinoElemento inquilinoElemento,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				InquilinoElementoDaoSql.SQL_FIND_ALL);

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(inquilinoElemento,
				startsWith);
		StringBuilder where = new StringBuilder(
				InquilinoElementoDaoSql.SQL_WHERE_ALL);
		where.append(mapaWhere.get("query"));
		query.append(where);

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

		if (jqGridRequestDto != null) {
			query = JQGridManager.getPaginationQuery(jqGridRequestDto, query);
		}

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the InquilinoElemento table.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllCount(InquilinoElemento inquilinoElemento) {
		StringBuilder query = new StringBuilder(
				InquilinoElementoDaoSql.SQL_FIND_ALL_COUNT);

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(inquilinoElemento);
		StringBuilder where = new StringBuilder(
				InquilinoElementoDaoSql.SQL_WHERE_ALL);
		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 InquilinoElemento table using like.
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @param startsWith
	 *            Boolean
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllLikeCount(InquilinoElemento inquilinoElemento,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				InquilinoElementoDaoSql.SQL_FIND_ALL_COUNT);

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(inquilinoElemento,
				startsWith);
		StringBuilder where = new StringBuilder(
				InquilinoElementoDaoSql.SQL_WHERE_ALL);
		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 InquilinoElemento selected for rup_table
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<TableRowDto<InquilinoElemento>>
	 */
	@Override
	public List<TableRowDto<InquilinoElemento>> reorderSelection(
			InquilinoElemento inquilinoElemento,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				InquilinoElementoDaoSql.SQL_FIND_ALL);

		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(inquilinoElemento,
				startsWith);
		StringBuilder where = new StringBuilder(
				InquilinoElementoDaoSql.SQL_WHERE_ALL);
		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, InquilinoElemento.class,
				filterParamList, InquilinoElementoDaoSql.PK);

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

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the InquilinoElemento entity
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento 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.
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereMap(InquilinoElemento inquilinoElemento) {

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

		if (inquilinoElemento != null) {
			if (inquilinoElemento.getContratoAlquilerElemento() != null) {
				// Id Contrato Alquier
				if (inquilinoElemento.getContratoAlquilerElemento()
						.getIdContratoAlquiler() != null) {
					BDUtils.crearFiltroIgual(where, params,
							"INQUELEM.ID_CONTRATO_ALQ", inquilinoElemento
									.getContratoAlquilerElemento()
									.getIdContratoAlquiler());
				}
			}
			// Id Inquilino
			if (inquilinoElemento.getIdInquilino() != null) {
				BDUtils.crearFiltroIgual(where, params,
						"INQUELEM.NUM_INQUILINO",
						inquilinoElemento.getIdInquilino());
			}
			if (inquilinoElemento.getPersona() != null) {
				// IdPersona
				if (inquilinoElemento.getPersona().getIdPersona() != null) {
					BDUtils.crearFiltroIgual(where, params,
							"INQUELEM.ID_PERSONA", inquilinoElemento
									.getPersona().getIdPersona());
				}
			}
		}

		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 InquilinoElemento entity
	 * 
	 * @param inquilinoElemento
	 *            InquilinoElemento 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.
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, Object> getWhereLikeMap(
			InquilinoElemento inquilinoElemento, Boolean startsWith) {

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

		if (inquilinoElemento != null) {
			if (inquilinoElemento.getContratoAlquilerElemento() != null) {
				// Id Contrato Alquier
				if (inquilinoElemento.getContratoAlquilerElemento()
						.getIdContratoAlquiler() != null) {
					BDUtils.crearFiltroIgual(where, params,
							"INQUELEM.ID_CONTRATO_ALQ", inquilinoElemento
									.getContratoAlquilerElemento()
									.getIdContratoAlquiler());
				}
			}
			// NumInquilino
			if (inquilinoElemento.getIdInquilino() != null) {
				BDUtils.crearFiltroIgual(where, params,
						"INQUELEM.ID_INQUILINO",
						inquilinoElemento.getIdInquilino());
			}
			if (inquilinoElemento.getPersona() != null) {
				// IdPersona
				if (inquilinoElemento.getPersona().getIdPersona() != null) {
					BDUtils.crearFiltroIgual(where, params,
							"INQUELEM.ID_PERSONA", inquilinoElemento
									.getPersona().getIdPersona());
				}
			}
		}

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