package com.ejie.m62fb.dao;

import com.ejie.x38.dto.Pagination;
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.m62fb.model.M62fbr44s0s00;

/**
 * M62fbr44s0s00DaoImpl generated by UDA, 17-oct-2012 15:03:38.
 * 
XXXX
 */

@Repository
@Transactional
public class M62fbr44s0s00DaoImpl implements M62fbr44s0s00Dao {
	private JdbcTemplate jdbcTemplate;
	private RowMapper<M62fbr44s0s00> rwMap = new RowMapper<M62fbr44s0s00>() {
		public M62fbr44s0s00 mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new M62fbr44s0s00(resultSet.getBigDecimal("IDM62R44T0"),
					resultSet.getBigDecimal("NUMVIVIENDA"),
					resultSet.getDate("FECINCORPORACIONCAT"),
					resultSet.getString("INDDISPONIBLE"),
					resultSet.getString("CODSITUACION"),
					resultSet.getDate("FECINISITUACION"),
					resultSet.getDate("FECFINSITUACION"),
					resultSet.getString("TEXOBSERVACIONES"),
					resultSet.getDate("FEHULTMODIF"),
					resultSet.getString("CODUSUULTMODIF"),
					resultSet.getInt("IDEREGISTRO"),
					resultSet.getDate("FECALTA"),
					resultSet.getString("EXCLUIDA"),
					resultSet.getBigDecimal("CSECUPRO"));
		}
	};

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

	/**
	 * Inserts a single row in the M62fbr44s0s00 table.
	 * 
	 * @param m62fbr44s0s00
	 *            Pagination
	 * @return M62fbr44s0s00
	 */
	public M62fbr44s0s00 add(M62fbr44s0s00 m62fbr44s0s00) {
		String query = "INSERT INTO M62R44T0S00 (ID_M62R44T0, NUM_VIVIENDA, FEC_INCORPORACION_CAT, IND_DISPONIBLE, COD_SITUACION, FEC_INI_SITUACION, FEC_FIN_SITUACION, TEX_OBSERVACIONES, FEH_ULT_MODIF, COD_USU_ULT_MODIF, IDE_REGISTRO, FEC_ALTA) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, m62fbr44s0s00.getIdM62r44t0(),
				m62fbr44s0s00.getNumVivienda(),
				m62fbr44s0s00.getFecIncorporacionCat(),
				m62fbr44s0s00.getIndDisponible(),
				m62fbr44s0s00.getCodSituacion(),
				m62fbr44s0s00.getFecIniSituacion(),
				m62fbr44s0s00.getFecFinSituacion(),
				m62fbr44s0s00.getTexObservaciones(),
				m62fbr44s0s00.getFehUltModif(),
				m62fbr44s0s00.getCodUsuUltModif(),
				m62fbr44s0s00.getIdeRegistro(), m62fbr44s0s00.getFecAlta());
		return m62fbr44s0s00;
	}

	/**
	 * Updates a single row in the M62fbr44s0s00 table.
	 * 
	 * @param m62fbr44s0s00
	 *            Pagination
	 * @return M62fbr44s0s00
	 */
	public M62fbr44s0s00 update(M62fbr44s0s00 m62fbr44s0s00) {
		String query = "UPDATE M62R44T0S00 SET  COD_SITUACION=? , FEC_INI_SITUACION=? , FEC_FIN_SITUACION=? , TEX_OBSERVACIONES=? ,FEH_ULT_MODIF=SYSDATE, COD_USU_ULT_MODIF=? WHERE NUM_VIVIENDA=?";
		this.jdbcTemplate.update(query, m62fbr44s0s00.getCodSituacion(),
				m62fbr44s0s00.getFecIniSituacion(),
				m62fbr44s0s00.getFecFinSituacion(),
				m62fbr44s0s00.getTexObservaciones(),
				m62fbr44s0s00.getCodUsuUltModif(),
				m62fbr44s0s00.getNumVivienda());
		return m62fbr44s0s00;
	}

	/**
	 * Finds a single row in the M62fbr44s0s00 table.
	 * 
	 * @param m62fbr44s0s00
	 *            Pagination
	 * @return M62fbr44s0s00
	 */
	@Transactional(readOnly = true, timeout = 500)
	public M62fbr44s0s00 find(M62fbr44s0s00 m62fbr44s0s00) {
		String query = "SELECT t1.ID_M62R44T0 IDM62R44T0, t1.NUM_VIVIENDA NUMVIVIENDA, t1.FEC_INCORPORACION_CAT FECINCORPORACIONCAT, t1.IND_DISPONIBLE INDDISPONIBLE, t1.COD_SITUACION CODSITUACION, t1.FEC_INI_SITUACION FECINISITUACION, t1.FEC_FIN_SITUACION FECFINSITUACION, t1.TEX_OBSERVACIONES TEXOBSERVACIONES, t1.FEH_ULT_MODIF FEHULTMODIF, t1.COD_USU_ULT_MODIF CODUSUULTMODIF, t1.IDE_REGISTRO IDEREGISTRO, t1.FEC_ALTA FECALTA, t2.EXCLUIDA EXCLUIDA, t2.CSECUPRO CSECUPRO FROM M62R44T0S00 t1, M62R01V0S00_DISP_VIVS t2  WHERE t1.NUM_VIVIENDA = ? AND t1.NUM_VIVIENDA = t2.NUM_VIVIENDA(+)  ";

		List<M62fbr44s0s00> m62fbr44s0s00List = this.jdbcTemplate.query(query,
				this.rwMap, m62fbr44s0s00.getNumVivienda());
		return (M62fbr44s0s00) DataAccessUtils.uniqueResult(m62fbr44s0s00List);
	}

	/**
	 * Removes a single row in the M62fbr44s0s00 table.
	 * 
	 * @param m62fbr44s0s00
	 *            Pagination
	 * @return
	 */
	public void remove(M62fbr44s0s00 m62fbr44s0s00) {
		String query = "DELETE FROM M62R44T0S00 WHERE NUM_VIVIENDA=?";
		this.jdbcTemplate.update(query, m62fbr44s0s00.getNumVivienda());
	}

	/**
	 * Finds a List of rows in the M62fbr44s0s00 table.
	 * 
	 * @param m62fbr44s0s00
	 *            M62fbr44s0s00
	 * @param pagination
	 *            Pagination
	 * @return List
	 */
	@Transactional(readOnly = true, timeout = 500)
	public List<M62fbr44s0s00> findAll(M62fbr44s0s00 m62fbr44s0s00,
			Pagination pagination) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_M62R44T0 IDM62R44T0,t1.NUM_VIVIENDA NUMVIVIENDA,t1.FEC_INCORPORACION_CAT FECINCORPORACIONCAT,t1.IND_DISPONIBLE INDDISPONIBLE,t1.COD_SITUACION CODSITUACION,t1.FEC_INI_SITUACION FECINISITUACION,t1.FEC_FIN_SITUACION FECFINSITUACION,t1.TEX_OBSERVACIONES TEXOBSERVACIONES,t1.FEH_ULT_MODIF FEHULTMODIF,t1.COD_USU_ULT_MODIF CODUSUULTMODIF,t1.IDE_REGISTRO IDEREGISTRO,t1.FEC_ALTA FECALTA, t2.EXCLUIDA EXCLUIDA, t2.CSECUPRO CSECUPRO ");
		query.append("FROM M62R44T0S00 t1, M62R01V0S00_DISP_VIVS t2 ");

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

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

		if (pagination != null) {
			query = pagination.getPaginationQuery(query);
		}

		return (List<M62fbr44s0s00>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

	/**
	 * Counts rows in the M62fbr44s0s00 table.
	 * 
	 * @param m62fbr44s0s00
	 *            M62fbr44s0s00
	 * @return Long
	 */
	@Transactional(readOnly = true, timeout = 500)
	public Long findAllCount(M62fbr44s0s00 m62fbr44s0s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM M62FBR44S0S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(m62fbr44s0s00);
		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());
	}

	/**
	 * Finds rows in the M62fbr44s0s00 table using like.
	 * 
	 * @param m62fbr44s0s00
	 *            M62fbr44s0s00
	 * @param pagination
	 *            Pagination
	 * @param startsWith
	 *            Boolean
	 * @return List
	 */
	@Transactional(readOnly = true, timeout = 500)
	public List<M62fbr44s0s00> findAllLike(M62fbr44s0s00 m62fbr44s0s00,
			Pagination pagination, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_M62R44T0 IDM62R44T0,t1.NUM_VIVIENDA NUMVIVIENDA,t1.FEC_INCORPORACION_CAT FECINCORPORACIONCAT,t1.IND_DISPONIBLE INDDISPONIBLE,t1.COD_SITUACION CODSITUACION,t1.FEC_INI_SITUACION FECINISITUACION,t1.FEC_FIN_SITUACION FECFINSITUACION,t1.TEX_OBSERVACIONES TEXOBSERVACIONES,t1.FEH_ULT_MODIF FEHULTMODIF,t1.COD_USU_ULT_MODIF CODUSUULTMODIF,t1.IDE_REGISTRO IDEREGISTRO,t1.FEC_ALTA FECALTA, t2.EXCLUIDA EXCLUIDA, t2.CSECUPRO CSECUPRO ");
		query.append("FROM M62R44T0S00 t1, M62R01V0S00_DISP_VIVS t2 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(m62fbr44s0s00,
				startsWith);
		StringBuilder where = new StringBuilder(
				" WHERE 1=1 AND t1.NUM_VIVIENDA = t2.NUM_VIVIENDA(+) ");
		where.append(mapaWhere.get("query"));
		query.append(where);

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

		if (pagination != null) {
			query = pagination.getPaginationQuery(query);
		}

		return (List<M62fbr44s0s00>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(m62fbr44s0s00,
				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());
	}

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

		StringBuffer where = new StringBuffer(
				M62fbr44s0s00DaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (m62fbr44s0s00 != null && m62fbr44s0s00.getIdM62r44t0() != null) {
			where.append(" AND t1.ID_M62R44T0 = ?");
			params.add(m62fbr44s0s00.getIdM62r44t0());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getNumVivienda() != null) {
			where.append(" AND t1.NUM_VIVIENDA = ?");
			params.add(m62fbr44s0s00.getNumVivienda());
		}
		if (m62fbr44s0s00 != null
				&& m62fbr44s0s00.getFecIncorporacionCat() != null) {
			where.append(" AND t1.FEC_INCORPORACION_CAT = ?");
			params.add(m62fbr44s0s00.getFecIncorporacionCat());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getIndDisponible() != null) {
			where.append(" AND t1.IND_DISPONIBLE = ?");
			params.add(m62fbr44s0s00.getIndDisponible());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getCodSituacion() != null) {
			where.append(" AND t1.COD_SITUACION = ?");
			params.add(m62fbr44s0s00.getCodSituacion());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFecIniSituacion() != null) {
			where.append(" AND t1.FEC_INI_SITUACION = ?");
			params.add(m62fbr44s0s00.getFecIniSituacion());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFecFinSituacion() != null) {
			where.append(" AND t1.FEC_FIN_SITUACION = ?");
			params.add(m62fbr44s0s00.getFecFinSituacion());
		}
		if (m62fbr44s0s00 != null
				&& m62fbr44s0s00.getTexObservaciones() != null) {
			where.append(" AND t1.TEX_OBSERVACIONES = ?");
			params.add(m62fbr44s0s00.getTexObservaciones());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFehUltModif() != null) {
			where.append(" AND t1.FEH_ULT_MODIF = ?");
			params.add(m62fbr44s0s00.getFehUltModif());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getCodUsuUltModif() != null) {
			where.append(" AND t1.COD_USU_ULT_MODIF = ?");
			params.add(m62fbr44s0s00.getCodUsuUltModif());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getIdeRegistro() != null) {
			where.append(" AND t1.IDE_REGISTRO = ?");
			params.add(m62fbr44s0s00.getIdeRegistro());
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFecAlta() != null) {
			where.append(" AND t1.FEC_ALTA = ?");
			params.add(m62fbr44s0s00.getFecAlta());
		}

		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 M62fbr44s0s00 entity
	 * 
	 * @param m62fbr44s0s00
	 *            M62fbr44s0s00 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, ?> getWhereLikeMap(M62fbr44s0s00 m62fbr44s0s00,
			Boolean startsWith) {

		StringBuffer where = new StringBuffer(
				M62fbr44s0s00DaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (m62fbr44s0s00 != null && m62fbr44s0s00.getIdM62r44t0() != null) {
			where.append(" AND t1.ID_M62R44T0 = ?");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getNumVivienda() != null) {
			where.append(" AND t1.NUM_VIVIENDA = ?");
		}
		if (m62fbr44s0s00 != null
				&& m62fbr44s0s00.getFecIncorporacionCat() != null) {
			where.append(" AND t1.FEC_INCORPORACION_CAT = ?");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getIndDisponible() != null) {
			where.append(" AND UPPER(t1.IND_DISPONIBLE) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(m62fbr44s0s00.getIndDisponible().toUpperCase() + "%");
			} else {
				params.add("%" + m62fbr44s0s00.getIndDisponible().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.IND_DISPONIBLE IS NOT NULL");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getCodSituacion() != null) {
			where.append(" AND UPPER(t1.COD_SITUACION) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(m62fbr44s0s00.getCodSituacion().toUpperCase() + "%");
			} else {
				params.add("%" + m62fbr44s0s00.getCodSituacion().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.COD_SITUACION IS NOT NULL");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFecIniSituacion() != null) {
			where.append(" AND t1.FEC_INI_SITUACION = ?");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFecFinSituacion() != null) {
			where.append(" AND t1.FEC_FIN_SITUACION = ?");
		}
		if (m62fbr44s0s00 != null
				&& m62fbr44s0s00.getTexObservaciones() != null) {
			where.append(" AND UPPER(t1.TEX_OBSERVACIONES) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(m62fbr44s0s00.getTexObservaciones().toUpperCase()
						+ "%");
			} else {
				params.add("%"
						+ m62fbr44s0s00.getTexObservaciones().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.TEX_OBSERVACIONES IS NOT NULL");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFehUltModif() != null) {
			where.append(" AND t1.FEH_ULT_MODIF = ?");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getCodUsuUltModif() != null) {
			where.append(" AND UPPER(t1.COD_USU_ULT_MODIF) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(m62fbr44s0s00.getCodUsuUltModif().toUpperCase()
						+ "%");
			} else {
				params.add("%"
						+ m62fbr44s0s00.getCodUsuUltModif().toUpperCase() + "%");
			}
			where.append(" AND t1.COD_USU_ULT_MODIF IS NOT NULL");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getIdeRegistro() != null) {
			where.append(" AND t1.IDE_REGISTRO = ?");
		}
		if (m62fbr44s0s00 != null && m62fbr44s0s00.getFecAlta() != null) {
			where.append(" AND t1.FEC_ALTA = ?");
		}

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

		return mapWhere;
	}

	/**
	 * Actualiza en una incidencia de la tabla Incidencias, los campos que no se
	 * hayan informado nulos
	 * 
	 * @param viviendas
	 *            M62fbr46s0s00
	 * @return M62fbr46s0s00
	 */
	public void addIncMasivaViv(M62fbr44s0s00 vivienda) {
		String indDisponible;
		if (vivienda.getCodSituacion().equals("D")) {
			indDisponible = "S";
		} else {
			indDisponible = "N";
		}
		String query = "INSERT INTO M62R44T0S00 "
				+ "(NUM_VIVIENDA, FEC_INCORPORACION_CAT, IND_DISPONIBLE, COD_SITUACION, FEC_INI_SITUACION, FEC_FIN_SITUACION, TEX_OBSERVACIONES ) "
				+ "VALUES (?,TRUNC(SYSDATE),?,?,?,?,?)";
		this.jdbcTemplate.update(query, vivienda.getNumVivienda(),
				indDisponible, vivienda.getCodSituacion(),
				vivienda.getFecIniSituacion(), vivienda.getFecFinSituacion(),
				vivienda.getTexObservaciones());
	}

	/**
	 * Counts rows in the M62fbr46s0s00 table.
	 * 
	 * @param m62fbr46s0s00
	 *            M62fbr46s0s00
	 * @return Long
	 */
	@Transactional(readOnly = true, timeout = 500)
	public Long valViviendasSel(String listadoVivs) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM M62R01V0S00_DISP_VIVS t1 WHERE SUBSTR (t1. NUM_EXPEDIENTE, 13, 2) <> 'VL' AND t1.NUM_VIVIENDA IN ("
						+ listadoVivs + ")");
		// que espere 4 minutos para dar un timeout
		// this.jdbcTemplate.setQueryTimeout(240);
		return this.jdbcTemplate.queryForLong(query.toString());
	}

	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

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