package com.ejie.aa20b.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.aa20b.model.Plantas;

/**
 * PlantasDaoImpl generated by UDA, 28-nov-2014 11:32:16.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class PlantasDaoImpl implements PlantasDao {
	private JdbcTemplate jdbcTemplate;
	private RowMapper<Plantas> rwMap = new RowMapper<Plantas>() {
		public Plantas mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Plantas(resultSet.getInt("IDPLANTA"),
					resultSet.getString("CPLANTA"),
					resultSet.getString("EPLANTA"),
					resultSet.getString("RPLANTA"),
					resultSet.getString("BAJA"), resultSet.getDate("FEINI"),
					resultSet.getInt("NUMPLANTA"));
		}
	};
	private RowMapper<Plantas> rwMapPlantas = new RowMapper<Plantas>() {
		public Plantas mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Plantas(resultSet.getInt("IDPLANTA"),
					resultSet.getString("CPLANTA"),
					resultSet.getString("EPLANTA"), null, null, null, null);
		}
	};

	/**
	 * 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 Plantas table.
	 * 
	 * @param plantas
	 *            Pagination
	 * @return Plantas
	 */
	public Plantas add(Plantas plantas) {

		// Obtener el id correlativo
		Long idCorrelativo = this.jdbcTemplate
				.queryForLong("SELECT PLANTA_SEQ.NEXTVAL FROM DUAL");

		String query = "INSERT INTO PLANTAS (IDPLANTA, CPLANTA, EPLANTA, RPLANTA, BAJA, FEINI, NUMPLANTA) VALUES (?,?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, idCorrelativo, plantas.getCplanta(),
				plantas.getEplanta(), plantas.getRplanta(),
				plantas.getBaja() == null ? "0" : plantas.getBaja(),
				plantas.getFeini(), plantas.getNumPlanta());
		return plantas;
	}

	/**
	 * Updates a single row in the Plantas table.
	 * 
	 * @param plantas
	 *            Pagination
	 * @return Plantas
	 */
	public Plantas update(Plantas plantas) {
		String query = "UPDATE PLANTAS SET CPLANTA=?, EPLANTA=?, RPLANTA=?, BAJA=?, FEINI=?, NUMPLANTA=? WHERE IDPLANTA=? ";

		this.jdbcTemplate.update(query, plantas.getCplanta(),
				plantas.getEplanta(), plantas.getRplanta(),
				plantas.getBaja() == null ? "0" : plantas.getBaja(),
				plantas.getFeini(), plantas.getNumPlanta(),
				plantas.getIdplanta());

		return plantas;
	}

	/**
	 * Finds a single row in the Plantas table.
	 * 
	 * @param plantas
	 *            Pagination
	 * @return Plantas
	 */
	@Transactional(readOnly = true)
	public Plantas find(Plantas plantas) {
		String query = "SELECT t1.IDPLANTA IDPLANTA, t1.CPLANTA CPLANTA, t1.EPLANTA EPLANTA, t1.RPLANTA RPLANTA, t1.BAJA BAJA, t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA FROM PLANTAS t1  WHERE t1.IDPLANTA = ?";

		List<Plantas> plantasList = this.jdbcTemplate.query(query, this.rwMap,
				plantas.getIdplanta());
		return (Plantas) DataAccessUtils.uniqueResult(plantasList);
	}

	/**
	 * Finds a single row in the Plantas table.
	 * 
	 * @param plantas
	 *            Pagination
	 * @return Plantas
	 */
	@Transactional(readOnly = true)
	public Plantas obtenerPlanta(Plantas plantas) {
		String query = "SELECT t1.IDPLANTA IDPLANTA, t1.CPLANTA CPLANTA, t1.EPLANTA EPLANTA, t1.RPLANTA RPLANTA, t1.BAJA BAJA, t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA FROM PLANTAS t1  WHERE t1.IDPLANTA = ?  ";

		List<Plantas> plantasList = this.jdbcTemplate.query(query, this.rwMap,
				plantas.getIdplanta());
		return (Plantas) DataAccessUtils.uniqueResult(plantasList);
	}

	/**
	 * Removes a single row in the Plantas table.
	 * 
	 * @param plantas
	 *            Pagination
	 * @return
	 */
	public void remove(Plantas plantas) {
		String query = "DELETE FROM PLANTAS WHERE IDPLANTA=? AND CPLANTA=? AND EPLANTA=? AND RPLANTA=? AND BAJA=? AND FEINI=? AND NUMPLANTA=?";
		this.jdbcTemplate.update(query, plantas.getIdplanta(),
				plantas.getCplanta(), plantas.getEplanta(),
				plantas.getRplanta(), plantas.getBaja(), plantas.getFeini(),
				plantas.getNumPlanta());
	}

	/**
	 * Finds a List of rows in the Plantas table.
	 * 
	 * @param plantas
	 *            Plantas
	 * @param pagination
	 *            Pagination
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Plantas> findAll(Plantas plantas, Pagination pagination) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDPLANTA IDPLANTA,t1.CPLANTA CPLANTA,t1.EPLANTA EPLANTA,t1.RPLANTA RPLANTA,t1.BAJA BAJA,t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA ");
		query.append("FROM PLANTAS t1 ");

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

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

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

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

	/**
	 * Obtener Plantas para el edificio y zona especificado.
	 * 
	 * @param codEdif
	 *            String
	 * @param codZona
	 *            Integer
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Plantas> obtenerPlantasEdifZona(String codEdif, Integer codZona) {
		StringBuilder query = new StringBuilder(
				"SELECT DISTINCT t1.IDPLANTA IDPLANTA, t1.CPLANTA CPLANTA, t1.EPLANTA EPLANTA, t1.RPLANTA RPLANTA, t1.BAJA BAJA, t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA ");
		query.append(" FROM PLANTAS t1, EDIF_ESTRUC t2 ");
		query.append(" WHERE t1.IDPLANTA=t2.IDPLANTA AND t2.IDEDIFICIO=? AND t2.IDZONA= ? ORDER BY t1.NUMPLANTA ");

		return (List<Plantas>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, codEdif, codZona);
	}

	@Transactional(readOnly = true)
	public List<Plantas> obtenerPlantasEdifZonaAlta(String codEdif,
			Integer codZona) {
		StringBuilder query = new StringBuilder(
				"SELECT DISTINCT t1.IDPLANTA IDPLANTA, t1.CPLANTA CPLANTA, t1.EPLANTA EPLANTA, t1.RPLANTA RPLANTA, t1.BAJA BAJA, t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA ");
		query.append(" FROM PLANTAS t1, EDIF_ESTRUC t2 ");
		query.append(" WHERE t1.IDPLANTA=t2.IDPLANTA AND t2.IDEDIFICIO=? AND t2.IDZONA= ? AND t1.SITUACION='A'  ORDER BY t1.NUMPLANTA  ");

		return (List<Plantas>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, codEdif, codZona);
	}

	/**
	 * Obtener Plantas para el edificio y zona especificado.
	 * 
	 * @param codEdif
	 *            String
	 * @param codZona
	 *            Integer
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Plantas> obtenerPlantasEdifZonaConPlanos(String codEdif,
			Integer codZona) {
		StringBuilder query = new StringBuilder(
				"SELECT DISTINCT t1.IDPLANTA IDPLANTA, t1.CPLANTA CPLANTA, t1.EPLANTA EPLANTA, t1.RPLANTA RPLANTA, t1.BAJA BAJA, t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA ");
		query.append(" FROM PLANTAS t1, PLANOS t2 ");
		query.append(" WHERE t1.IDPLANTA=t2.IDPLANTA AND t2.IDEDIFICIO=? AND t2.IDZONA= ? ORDER BY t1.NUMPLANTA ");

		return (List<Plantas>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, codEdif, codZona);
	}

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(plantas);
		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 Plantas table using like.
	 * 
	 * @param plantas
	 *            Plantas
	 * @param pagination
	 *            Pagination
	 * @param startsWith
	 *            Boolean
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Plantas> findAllLike(Plantas plantas, Pagination pagination,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDPLANTA IDPLANTA,t1.CPLANTA CPLANTA,t1.EPLANTA EPLANTA,t1.RPLANTA RPLANTA,t1.BAJA BAJA,t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA ");
		query.append("FROM PLANTAS t1 ");

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

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

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

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

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

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

	/**
	 * Obtiene la lista de Plantas
	 * 
	 * @param codZona
	 *            String
	 * @param codEdificio
	 *            String
	 * @param language
	 *            String
	 * @return List<Plantas>
	 */
	public List<Plantas> obtenerPlantasZonaLibres(String codEdificio,
			String codZona, String language) {

		StringBuffer select = new StringBuffer();
		select.append("SELECT PL.IDPLANTA, PL.CPLANTA, PL.EPLANTA, PL.NUMPLANTA FROM PLANTAS PL WHERE PL.BAJA='0' OR PL.BAJA IS NULL ");
		select.append("MINUS ");
		select.append("SELECT PL.IDPLANTA, PL.CPLANTA, PL.EPLANTA, PL.NUMPLANTA FROM PLANTAS PL, EDIF_ESTRUC ES ");
		select.append("WHERE ES.IDEDIFICIO=?");
		select.append("AND ES.IDZONA=?");
		select.append("AND PL.IDPLANTA=ES.IDPLANTA ");

		/*
		 * if (language.equalsIgnoreCase("es"))
		 * select.append("ORDER BY CPLANTA"); else
		 * select.append("ORDER BY EPLANTA");
		 */
		select.append("ORDER BY NUMPLANTA");
		return (List<Plantas>) this.jdbcTemplate.query(select.toString(),
				this.rwMapPlantas, codEdificio, codZona);

	}

	/**
	 * Obtiene la lista de zonas
	 * 
	 * @param idZonaSeleccionado
	 * @return
	 */
	public List<Plantas> obtenerPlantasZonaOcupadas(String codEdificio,
			String codZona, String language) {

		StringBuffer select = new StringBuffer();
		select.append("SELECT DISTINCT PL.IDPLANTA, PL.CPLANTA, PL.EPLANTA, PL.NUMPLANTA FROM PLANTAS PL, EDIF_ESTRUC ES ");
		select.append("WHERE ES.IDPLANTA<>0 AND ES.IDEDIFICIO=?");
		select.append("AND ES.IDZONA=?");
		select.append("AND PL.IDPLANTA=ES.IDPLANTA ");

		/*
		 * if (language.equalsIgnoreCase("es"))
		 * select.append("ORDER BY CPLANTA"); else
		 * select.append("ORDER BY EPLANTA");
		 */
		select.append("ORDER BY NUMPLANTA");

		return (List<Plantas>) this.jdbcTemplate.query(select.toString(),
				this.rwMapPlantas, codEdificio, codZona);

	}

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

		StringBuilder where = new StringBuilder(
				PlantasDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();
		where.append(" AND t1.SITUACION = 'A'");
		if (plantas != null && plantas.getIdplanta() != null) {
			where.append(" AND t1.IDPLANTA = ?");
			params.add(plantas.getIdplanta());
		}
		if (plantas != null && plantas.getCplanta() != null) {
			where.append(" AND t1.CPLANTA = ?");
			params.add(plantas.getCplanta());
		}
		if (plantas != null && plantas.getEplanta() != null) {
			where.append(" AND t1.EPLANTA = ?");
			params.add(plantas.getEplanta());
		}
		if (plantas != null && plantas.getRplanta() != null) {
			where.append(" AND t1.RPLANTA = ?");
			params.add(plantas.getRplanta());
		}
		if (plantas != null && plantas.getBaja() != null) {
			where.append(" AND t1.BAJA = ?");
			params.add(plantas.getBaja());
		}
		if (plantas != null && plantas.getFeini() != null) {
			where.append(" AND t1.FEINI = ?");
			params.add(plantas.getFeini());
		}
		if (plantas != null && plantas.getNumPlanta() != null) {
			where.append(" AND t1.NUMPLANTA = ?");
			params.add(plantas.getNumPlanta());
		}

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

		StringBuilder where = new StringBuilder(
				PlantasDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();
		where.append(" AND t1.SITUACION = 'A'");
		if (plantas != null && plantas.getIdplanta() != null) {
			where.append(" AND t1.IDPLANTA = ?");
			params.add(plantas.getIdplanta());
		}
		if (plantas != null && plantas.getCplanta() != null) {
			where.append(" AND UPPER(t1.CPLANTA) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(plantas.getCplanta().toUpperCase() + "%");
			} else {
				params.add("%" + plantas.getCplanta().toUpperCase() + "%");
			}
			where.append(" AND t1.CPLANTA IS NOT NULL");
		}
		if (plantas != null && plantas.getEplanta() != null) {
			where.append(" AND UPPER(t1.EPLANTA) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(plantas.getEplanta().toUpperCase() + "%");
			} else {
				params.add("%" + plantas.getEplanta().toUpperCase() + "%");
			}
			where.append(" AND t1.EPLANTA IS NOT NULL");
		}
		if (plantas != null && plantas.getRplanta() != null) {
			where.append(" AND UPPER(t1.RPLANTA) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(plantas.getRplanta().toUpperCase() + "%");
			} else {
				params.add("%" + plantas.getRplanta().toUpperCase() + "%");
			}
			where.append(" AND t1.RPLANTA IS NOT NULL");
		}
		if (plantas != null && plantas.getBaja() != null) {
			where.append(" AND UPPER(t1.BAJA) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(plantas.getBaja().toUpperCase() + "%");
			} else {
				params.add("%" + plantas.getBaja().toUpperCase() + "%");
			}
			where.append(" AND t1.BAJA IS NOT NULL");
		}
		if (plantas != null && plantas.getFeini() != null) {
			where.append(" AND t1.FEINI = ?");
			params.add(plantas.getFeini());
		}
		if (plantas != null && plantas.getNumPlanta() != null) {
			where.append(" AND t1.NUMPLANTA = ?");
			params.add(plantas.getNumPlanta());
		}

		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;

	@Transactional(readOnly = true)
	public Plantas obtenerPlantaDesdeXlnets(Plantas plantas) {
		String query = "SELECT t1.IDPLANTA IDPLANTA, t1.CPLANTA CPLANTA, t1.EPLANTA EPLANTA, t1.RPLANTA RPLANTA, t1.BAJA BAJA, t1.FEINI FEINI, t1.NUMPLANTA NUMPLANTA FROM PLANTAS t1  WHERE t1.CODPLANTA = ? AND t1.SITUACION='A'  ";

		List<Plantas> plantasList = this.jdbcTemplate.query(query, this.rwMap,
				plantas.getCodPlanta());
		/*
		 * if (plantasList != null && plantasList.size() > 1) { return
		 * plantasList.get(0); } else {
		 */
		return (Plantas) DataAccessUtils.uniqueResult(plantasList);
		// }
	}
}
