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.Cuestionario;

/**
 * CuestionarioDaoImpl generated by UDA, 02-mar-2015 11:32:36.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class CuestionarioDaoImpl implements CuestionarioDao {
	private JdbcTemplate jdbcTemplate;
	private RowMapper<Cuestionario> rwMap = new RowMapper<Cuestionario>() {
		public Cuestionario mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Cuestionario(resultSet.getInt("IDCUESTIONARIO"),
					resultSet.getLong("IDGAMA"), resultSet.getLong("NROORDEN"),
					resultSet.getString("OPERACION"),
					resultSet.getLong("SEMANAS"), resultSet.getLong("TIEMPO"),
					resultSet.getString("PREVISTO"));
		}
	};

	/**
	 * 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 Cuestionario table.
	 * 
	 * @param cuestionario
	 *            Pagination
	 * @return Cuestionario
	 */
	public Cuestionario add(Cuestionario cuestionario) {
		final Integer nextId = this.jdbcTemplate
				.queryForInt("SELECT CUESTIONARIO_SEQ.NEXTVAL FROM DUAL");

		cuestionario.setIdcuestionario(nextId);

		String query = "INSERT INTO CUESTIONARIO (IDCUESTIONARIO, IDGAMA, NROORDEN, OPERACION, SEMANAS, TIEMPO, PREVISTO) VALUES (?,?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, cuestionario.getIdcuestionario(),
				cuestionario.getIdgama(), cuestionario.getNroorden(),
				cuestionario.getOperacion(), cuestionario.getSemanas(),
				cuestionario.getTiempo(), cuestionario.getPrevisto());
		return cuestionario;
	}

	/**
	 * Updates a single row in the Cuestionario table.
	 * 
	 * @param cuestionario
	 *            Pagination
	 * @return Cuestionario
	 */
	public Cuestionario update(Cuestionario cuestionario) {
		String query = "UPDATE CUESTIONARIO SET NROORDEN=?, OPERACION=?, SEMANAS=?, TIEMPO=? WHERE IDCUESTIONARIO=?";
		this.jdbcTemplate.update(query, cuestionario.getNroorden(),
				cuestionario.getOperacion(), cuestionario.getSemanas(),
				cuestionario.getTiempo(), cuestionario.getIdcuestionario());
		return cuestionario;
	}

	/**
	 * Finds a single row in the Cuestionario table.
	 * 
	 * @param cuestionario
	 *            Pagination
	 * @return Cuestionario
	 */
	@Transactional(readOnly = true)
	public Cuestionario find(Cuestionario cuestionario) {
		String query = "SELECT t1.IDCUESTIONARIO IDCUESTIONARIO, t1.IDGAMA IDGAMA, t1.NROORDEN NROORDEN, t1.OPERACION OPERACION, t1.SEMANAS SEMANAS, t1.TIEMPO TIEMPO, t1.PREVISTO PREVISTO FROM CUESTIONARIO t1  WHERE t1.IDCUESTIONARIO = ?  ";

		List<Cuestionario> cuestionarioList = this.jdbcTemplate.query(query,
				this.rwMap, cuestionario.getIdcuestionario());
		return (Cuestionario) DataAccessUtils.uniqueResult(cuestionarioList);
	}

	/**
	 * Removes a single row in the Cuestionario table.
	 * 
	 * @param cuestionario
	 *            Pagination
	 * @return
	 */
	public void remove(Cuestionario cuestionario) {
		String query = "DELETE FROM CUESTIONARIO WHERE IDCUESTIONARIO=?";
		this.jdbcTemplate.update(query, cuestionario.getIdcuestionario());
	}

	/**
	 * Finds a List of rows in the Cuestionario table.
	 * 
	 * @param cuestionario
	 *            Cuestionario
	 * @param pagination
	 *            Pagination
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Cuestionario> findAll(Cuestionario cuestionario,
			Pagination pagination) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDCUESTIONARIO IDCUESTIONARIO,t1.IDGAMA IDGAMA,t1.NROORDEN NROORDEN,t1.OPERACION OPERACION,t1.SEMANAS SEMANAS,t1.TIEMPO TIEMPO,t1.PREVISTO PREVISTO ");
		query.append("FROM CUESTIONARIO t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(cuestionario);
		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<Cuestionario>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(cuestionario);
		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 Cuestionario table using like.
	 * 
	 * @param cuestionario
	 *            Cuestionario
	 * @param pagination
	 *            Pagination
	 * @param startsWith
	 *            Boolean
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Cuestionario> findAllLike(Cuestionario cuestionario,
			Pagination pagination, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDCUESTIONARIO IDCUESTIONARIO,t1.IDGAMA IDGAMA,t1.NROORDEN NROORDEN,t1.OPERACION OPERACION,t1.SEMANAS SEMANAS,t1.TIEMPO TIEMPO,t1.PREVISTO PREVISTO ");
		query.append("FROM CUESTIONARIO t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(cuestionario,
				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<Cuestionario>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

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

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

	/**
	 * obtener el número de orden máximo para una gama dada.
	 * 
	 * @param idGama
	 *            Long
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long obtenerMaxOrdenGama(Long idGama) {
		StringBuilder query = new StringBuilder(
				"SELECT MAX(t1.NROORDEN) FROM CUESTIONARIO t1 WHERE t1.IDGAMA= ?");

		Long maxOrden = this.jdbcTemplate
				.queryForLong(query.toString(), idGama);
		return maxOrden;
	}

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

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

		if (cuestionario != null && cuestionario.getIdcuestionario() != null) {
			where.append(" AND t1.IDCUESTIONARIO = ?");
			params.add(cuestionario.getIdcuestionario());
		}
		if (cuestionario != null && cuestionario.getIdgama() != null) {
			where.append(" AND t1.IDGAMA = ?");
			params.add(cuestionario.getIdgama());
		}
		if (cuestionario != null && cuestionario.getNroorden() != null) {
			where.append(" AND t1.NROORDEN = ?");
			params.add(cuestionario.getNroorden());
		}
		if (cuestionario != null && cuestionario.getOperacion() != null) {
			where.append(" AND t1.OPERACION = ?");
			params.add(cuestionario.getOperacion());
		}
		if (cuestionario != null && cuestionario.getSemanas() != null) {
			where.append(" AND t1.SEMANAS = ?");
			params.add(cuestionario.getSemanas());
		}
		if (cuestionario != null && cuestionario.getTiempo() != null) {
			where.append(" AND t1.TIEMPO = ?");
			params.add(cuestionario.getTiempo());
		}
		if (cuestionario != null && cuestionario.getPrevisto() != null) {
			where.append(" AND t1.PREVISTO = ?");
			params.add(cuestionario.getPrevisto());
		}

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

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

		if (cuestionario != null && cuestionario.getIdcuestionario() != null) {
			where.append(" AND t1.IDCUESTIONARIO = ?");
			params.add(cuestionario.getIdcuestionario());
		}
		if (cuestionario != null && cuestionario.getIdgama() != null) {
			where.append(" AND t1.IDGAMA = ?");
			params.add(cuestionario.getIdgama());
		}
		if (cuestionario != null && cuestionario.getNroorden() != null) {
			where.append(" AND t1.NROORDEN = ?");
			params.add(cuestionario.getNroorden());
		}
		if (cuestionario != null && cuestionario.getOperacion() != null) {
			where.append(" AND UPPER(t1.OPERACION) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(cuestionario.getOperacion().toUpperCase() + "%");
			} else {
				params.add("%" + cuestionario.getOperacion().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.OPERACION IS NOT NULL");
		}
		if (cuestionario != null && cuestionario.getSemanas() != null) {
			where.append(" AND t1.SEMANAS = ?");
			params.add(cuestionario.getSemanas());
		}
		if (cuestionario != null && cuestionario.getTiempo() != null) {
			where.append(" AND t1.TIEMPO = ?");
			params.add(cuestionario.getTiempo());
		}
		if (cuestionario != null && cuestionario.getPrevisto() != null) {
			where.append(" AND UPPER(t1.PREVISTO) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(cuestionario.getPrevisto().toUpperCase() + "%");
			} else {
				params.add("%" + cuestionario.getPrevisto().toUpperCase() + "%");
			}
			where.append(" AND t1.PREVISTO IS NOT NULL");
		}

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