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.ExpedienteVivienda;
import com.ejie.m62fb.model.Inquilino;
import com.ejie.m62fb.model.Vivienda;
import com.ejie.m62fb.model.persona.Persona;
import com.ejie.m62fb.model.tipos.TipoSiNo;
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;

/**
 * InquilinoDaoImpl generated by UDA, 21-oct-2015 14:17:46.
 * 
XXXX
 */

@Repository
@Transactional
public class InquilinoDaoImpl implements InquilinoDao {

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

	@Autowired
	PersonaDao personaDao;

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private final RowMapper<Inquilino> rwMap = new RowMapper<Inquilino>() {
		@SuppressWarnings("unchecked")
		@Override
		public Inquilino mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			Inquilino inquilino = new Inquilino();

			// Id Inquilino
			inquilino.setNumInquilino(resultSet.getBigDecimal("NUMINQUILINO"));

			// Id Vivienda
			inquilino.setVivienda(new Vivienda());
			inquilino.getVivienda().setNumVivienda(
					UtilsResulSet.getBigDecimal(resultSet, "NUMVIVIENDA"));

			// Num. Expediente
			inquilino.setExpedienteVivienda(new ExpedienteVivienda());
			inquilino.getExpedienteVivienda().setNumExpediente(
					resultSet.getString("NUMEXPEDIENTE"));

			// Fecha Alta
			inquilino.setFecAlta(resultSet.getTimestamp("FECALTA"));

			// Fecha/Hora Ultima Modificacion
			inquilino.setFecHorUltimaModif(resultSet
					.getTimestamp("FEHULTMODIF"));

			// Codigo Usuario Ultima Moficacion
			inquilino.setCodUsuarioUltimaModif(resultSet
					.getString("CODUSUULTMODIF"));

			// Persona
			Persona persona = new Persona(resultSet.getBigDecimal("IDPERSONA"));
			inquilino.setPersona(personaDao.find(persona));

			// Indicador Vivienda Adaptada
			TipoSiNo indVivAdaptada = new TipoSiNo(
					resultSet.getString("INDVIVADAPTADA"));
			inquilino.setIndVivAdaptada((TipoSiNo) comboP28Dao
					.find(indVivAdaptada));

			// Indicador Envio Registro Propio
			TipoSiNo indEnvRegProp = new TipoSiNo(
					resultSet.getString("INDENVREGPROP"));
			inquilino.setIndEnvRegProp((TipoSiNo) comboP28Dao
					.find(indEnvRegProp));

			// Id. Contrato
			inquilino.setIdContrato(resultSet.getInt("IDCONTRATO"));
			
			// IdM62R06T0
			inquilino.setIdM62r06t0(resultSet.getInt("IDM62R06T0"));
			
			return inquilino;
		}
	};

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

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

		// Campos para la generación del titular
		// Id Vivienda
		BigDecimal getIdViviendaAux = null;
		if (inquilino.getVivienda() != null
				&& inquilino.getVivienda().getNumVivienda() != null) {
			getIdViviendaAux = inquilino.getVivienda().getNumVivienda();
		}
		// Num. Expediente
		String getNumExpedienteAux = null;
		if (inquilino.getExpedienteVivienda() != null
				&& inquilino.getExpedienteVivienda().getNumExpediente() != null) {
			getNumExpedienteAux = inquilino.getExpedienteVivienda()
					.getNumExpediente();
		}
		// Persona (NIFTITULAR)
		String getCodIdPersona = null;
		if (inquilino.getPersona() != null
				&& inquilino.getPersona().getCodigoId() != null) {
			getCodIdPersona = inquilino.getPersona().getCodigoId();
		}
		// Id Persona
		BigDecimal getIdPersona = null;
		if (inquilino.getPersona() != null
				&& inquilino.getPersona().getIdPersona() != null) {
			getIdPersona = inquilino.getPersona().getIdPersona();
		}

		// Preparar Parametros
		List<Object> params = new ArrayList<Object>();
		// Id Vivienda
		params.add(getIdViviendaAux);
		// Num. Expediente
		params.add(getNumExpedienteAux);
		// Id Inquilino
		params.add(inquilino.getNumInquilino());
		// Id Persona
		params.add(getIdPersona);
		// Indicador Vivienda Adaptada
		if (inquilino.getIndVivAdaptada() != null) {
			params.add(inquilino.getIndVivAdaptada().getCodTabla());
		} else {
			params.add(BDUtils.FALSE);
		}
		// Indicador Envio Reg. Propio
		if (inquilino.getIndEnvRegProp() != null) {
			params.add(inquilino.getIndEnvRegProp().getCodTabla());
		} else {
			params.add(BDUtils.FALSE);
		}

		// Id Contrato
		params.add(inquilino.getIdContrato());
		
		// CodUsuario
		SQLGenericas.getParamsAbstractClass(params, inquilino);

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

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

		// Campos para la generación del titular
		
		// Num. Expediente
		String getNumExpedienteAux = null;
		if (inquilino.getExpedienteVivienda() != null
				&& inquilino.getExpedienteVivienda().getNumExpediente() != null) {
			getNumExpedienteAux = inquilino.getExpedienteVivienda()
					.getNumExpediente();
		}
		// Preparar Parametros
		List<Object> params = new ArrayList<Object>();
		// Num. Expediente
		params.add(getNumExpedienteAux);
		// Indicador Vivienda Adaptada
		if (inquilino.getIndVivAdaptada() != null) {
			params.add(inquilino.getIndVivAdaptada().getCodTabla());
		} else {
			params.add(BDUtils.FALSE);
		}
		// Indicador Envio Reg. Propio
		if (inquilino.getIndEnvRegProp() != null) {
			params.add(inquilino.getIndEnvRegProp().getCodTabla());
		} else {
			params.add(BDUtils.FALSE);
		}

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

		// Campos WHERE
		// Id_M62R06T0
		params.add(inquilino.getIdM62r06t0());

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

	/**
	 * Finds a single row in the Inquilino table.
	 * 
	 * @param inquilino
	 *            Inquilino
	 * @return Inquilino
	 */
	@Override
	@Transactional(readOnly = true)
	public Inquilino find(Inquilino inquilino) {
		String query = InquilinoDaoSql.SQL_FIND;
		List<Inquilino> inquilinoList = this.jdbcTemplate.query(query,this.rwMap, inquilino.getIdM62r06t0());
		return DataAccessUtils.uniqueResult(inquilinoList);
	}

	/**
	 * FindForUpdate
	 * 
	 * @param inquilino
	 *            Inquilino
	 * @return Inquilino
	 */
	@Override
	public Inquilino findForUpdate(Inquilino inquilino) {
		Inquilino inquilinoBD;
		try {
			inquilinoBD = this.jdbcTemplate.queryForObject(
					InquilinoDaoSql.SQL_FIND_FOR_UPDATE, this.rwMap, inquilino
							.getVivienda().getNumVivienda(), inquilino
							.getNumInquilino(), inquilino.getPersona()
							.getIdPersona(), inquilino.getFecHorUltimaModif());
		} catch (EmptyResultDataAccessException e) {
			throw new UFException(IberErrorsMsgConstants.CONCURRENCY_MSG);
		}
		if (inquilinoBD == null) {
			throw new UFException(IberErrorsMsgConstants.CONCURRENCY_MSG);
		}
		return inquilinoBD;
	}

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

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(inquilino);
		StringBuilder where = new StringBuilder(InquilinoDaoSql.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 Inquilino table using like.
	 * 
	 * @param inquilino
	 *            Inquilino
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<Inquilino>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Inquilino> findAllLike(Inquilino inquilino,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(InquilinoDaoSql.SQL_FIND_ALL);

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(inquilino, startsWith);
		StringBuilder where = new StringBuilder(InquilinoDaoSql.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 Inquilino table.
	 * 
	 * @param inquilino
	 *            Inquilino
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllCount(Inquilino inquilino) {
		StringBuilder query = new StringBuilder(
				InquilinoDaoSql.SQL_FIND_ALL_COUNT);

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

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

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

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

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Inquilino entity
	 * 
	 * @param inquilino
	 *            Inquilino 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(Inquilino inquilino) {

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

		if (inquilino != null) {
			if (inquilino.getVivienda() != null) {
				// NumVivienda
				if (inquilino.getVivienda().getNumVivienda() != null) {
					BDUtils.crearFiltroIgual(where, params,
							"INQU.NUM_VIVIENDA", inquilino.getVivienda()
									.getNumVivienda());
				}
			}
			// NumInquilino
			if (inquilino.getNumInquilino() != null) {
				BDUtils.crearFiltroIgual(where, params, "INQU.NUM_INQUILINO",
						inquilino.getNumInquilino());
			}
			if (inquilino.getPersona() != null) {
				// IdPersona
				if (inquilino.getPersona().getIdPersona() != null) {
					BDUtils.crearFiltroIgual(where, params, "INQU.ID_PERSONA",
							inquilino.getPersona().getIdPersona());
				}
			}
			// Id Contrato
			if (inquilino.getIdContrato() != null) {
				BDUtils.crearFiltroIgual(where, params, "INQU.ID_CONTRATO",
						inquilino.getIdContrato());
			}
		}

		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 Inquilino entity
	 * 
	 * @param inquilino
	 *            Inquilino 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(Inquilino inquilino,
			Boolean startsWith) {

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

		if (inquilino != null) {
			if (inquilino.getVivienda() != null) {
				// NumVivienda
				if (inquilino.getVivienda().getNumVivienda() != null) {
					BDUtils.crearFiltroIgual(where, params,
							"INQU.NUM_VIVIENDA", inquilino.getVivienda()
									.getNumVivienda());
				}
			}
			// NumInquilino
			if (inquilino.getNumInquilino() != null) {
				BDUtils.crearFiltroIgual(where, params, "INQU.NUM_INQUILINO",
						inquilino.getNumInquilino());
			}
			if (inquilino.getPersona() != null) {
				// IdPersona
				if (inquilino.getPersona().getIdPersona() != null) {
					BDUtils.crearFiltroIgual(where, params, "INQU.ID_PERSONA",
							inquilino.getPersona().getIdPersona());
				}
			}
			// Id Contrato
			if (inquilino.getIdContrato() != null) {
				BDUtils.crearFiltroIgual(where, params, "INQU.ID_CONTRATO",
						inquilino.getIdContrato());
			}
		}

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