package com.ejie.ab04b.dao.eventos;

import java.sql.PreparedStatement;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.OracleLobHandler;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ejie.ab04b.constantes.Constantes;
import com.ejie.ab04b.constantes.Secuencias;
import com.ejie.ab04b.model.eventos.ErrorEventoCola;
import com.ejie.ab04b.util.UtilSQL;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;

/**
 * ErrorEventoColaDaoImpl generated by UDA, 26-sep-2013 8:23:19.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class ErrorEventoColaDaoImpl implements ErrorEventoColaDao {

	private JdbcTemplate jdbcTemplate;

	/**
	 * logger
	 */
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ErrorEventoColaDaoImpl.class);

	private RowMapper<ErrorEventoCola> rwMap = new RowMapper<ErrorEventoCola>() {
		public ErrorEventoCola mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new ErrorEventoCola(resultSet.getInt("CODERROR"),
					resultSet.getString("TIPOPROC"),
					new OracleLobHandler().getClobAsString(resultSet, "EVENTO"),
					new OracleLobHandler().getClobAsString(resultSet, "ERROR"));
		}
	};

	/**
	 * Method use to set the XA datasource.
	 * 
	 *  dataSourceXA
	 *            DataSource
	 *
	 * @param dataSourceXA the new data source XA
	 */
	@Resource()
	public void setDataSourceXA(DataSource dataSourceXA) {
		this.jdbcTemplate = new JdbcTemplate(dataSourceXA);

	}

	/**
	 * Inserts a single row in the ErrorEventoCola table.
	 * 
	 *  erroreventocola
	 *            JQGridRequestDto
	 *  ErrorEventoCola
	 *
	 * @param erroreventocola the erroreventocola
	 * @return the error evento cola
	 */
	public ErrorEventoCola add(final ErrorEventoCola erroreventocola) {
		String query = "INSERT INTO AB0499S00 (CODERROR, TIPOPROC, EVENTO, ERROR) VALUES (?,?,?,?)";

		erroreventocola.setCoderror(
				Secuencias.ERROR_EVENTO_COLA.getNextInteger(jdbcTemplate));

		StringBuilder traza = new StringBuilder(
				"[ErrorEventoColaDaoImpl]: add ");
		traza.append(query.toString());
		traza.append("\n");
		traza.append("Parametros: ").append(erroreventocola.getCoderror())
				.append(", ").append(erroreventocola.getTipoproc()).append(", ")
				.append(erroreventocola.getEvento()).append(", ")
				.append(erroreventocola.getError());
		ErrorEventoColaDaoImpl.LOGGER.info(traza.toString());

		this.jdbcTemplate.execute(query,
				new AbstractLobCreatingPreparedStatementCallback(
						new OracleLobHandler()) {
					@Override()
					protected void setValues(PreparedStatement ps,
							LobCreator lobCreator)
							throws SQLException, DataAccessException {
						ps.setInt(Constantes.PS_1,
								erroreventocola.getCoderror().intValue());
						ps.setString(Constantes.PS_2,
								erroreventocola.getTipoproc());
						lobCreator.setClobAsString(ps, Constantes.PS_3,
								erroreventocola.getEvento());
						lobCreator.setClobAsString(ps, Constantes.PS_4,
								erroreventocola.getError());
					}
				});
		return erroreventocola;
	}

	/**
	 * Updates a single row in the ErrorEventoCola table.
	 * 
	 *  erroreventocola
	 *            JQGridRequestDto
	 *  ErrorEventoCola
	 *
	 * @param erroreventocola the erroreventocola
	 * @return the error evento cola
	 */
	public ErrorEventoCola update(ErrorEventoCola erroreventocola) {
		String query = "UPDATE AB0499S00 SET TIPOPROC=?, EVENTO=?, ERROR=? WHERE CODERROR=?";

		StringBuilder traza = new StringBuilder(
				"[ErrorEventoColaDaoImpl]: update ");
		traza.append(query.toString());
		traza.append("\n");
		traza.append("Parametros: ").append(erroreventocola.getTipoproc())
				.append(", ").append(erroreventocola.getEvento()).append(", ")
				.append(erroreventocola.getError()).append(", ")
				.append(erroreventocola.getCoderror());
		ErrorEventoColaDaoImpl.LOGGER.info(traza.toString());

		this.jdbcTemplate.update(query, erroreventocola.getTipoproc(),
				erroreventocola.getEvento(), erroreventocola.getError(),
				erroreventocola.getCoderror());
		return erroreventocola;
	}

	/**
	 * Finds a single row in the ErrorEventoCola table.
	 * 
	 *  erroreventocola
	 *            JQGridRequestDto
	 *  ErrorEventoCola
	 *
	 * @param erroreventocola the erroreventocola
	 * @return the error evento cola
	 */
	@Transactional(readOnly = true)
	public ErrorEventoCola find(ErrorEventoCola erroreventocola) {
		String query = "SELECT t1.CODERROR CODERROR, t1.TIPOPROC TIPOPROC, t1.EVENTO EVENTO, t1.ERROR ERROR FROM AB0499S00 t1  WHERE t1.CODERROR = ?  ";

		StringBuilder traza = new StringBuilder(
				"[ErrorEventoColaDaoImpl]: find ");
		traza.append(query.toString());
		traza.append("\n");
		traza.append("Parametros: ").append(erroreventocola.getCoderror());
		ErrorEventoColaDaoImpl.LOGGER.info(traza.toString());

		List<ErrorEventoCola> erroreventocolaList = this.jdbcTemplate
				.query(query, this.rwMap, erroreventocola.getCoderror());
		return (ErrorEventoCola) DataAccessUtils
				.uniqueResult(erroreventocolaList);
	}

	/**
	 * Removes a single row in the ErrorEventoCola table.
	 * 
	 *  erroreventocola
	 *            JQGridRequestDto
	 *
	 * @param erroreventocola the erroreventocola
	 */
	public void remove(ErrorEventoCola erroreventocola) {
		String query = "DELETE FROM AB0499S00 WHERE CODERROR=?";

		StringBuilder traza = new StringBuilder(
				"[ErrorEventoColaDaoImpl]: find ");
		traza.append(query.toString());
		traza.append("\n");
		traza.append("Parametros: ").append(erroreventocola.getCoderror());
		ErrorEventoColaDaoImpl.LOGGER.info(traza.toString());

		this.jdbcTemplate.update(query, erroreventocola.getCoderror());
	}

	/**
	 * Finds a List of rows in the ErrorEventoCola table.
	 * 
	 *  erroreventocola
	 *            ErrorEventoCola
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List
	 *
	 * @param erroreventocola the erroreventocola
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<ErrorEventoCola> findAll(ErrorEventoCola erroreventocola,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.CODERROR CODERROR,t1.TIPOPROC TIPOPROC,t1.EVENTO EVENTO,t1.ERROR ERROR ");
		query.append("FROM AB0499S00 t1 ");

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

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

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

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

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(erroreventocola);
		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 ErrorEventoCola entity
	 * 
	 *  erroreventocola
	 *            ErrorEventoCola Bean with the criteria values to filter by.
	 *  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.
	 *
	 * @param erroreventocola the erroreventocola
	 * @return the where map
	 */
	private Map<String, ?> getWhereMap(ErrorEventoCola erroreventocola) {

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

		if (erroreventocola != null) {
			if (erroreventocola.getCoderror() != null) {
				UtilSQL.preparaCampoSQL("t1.CODERROR",
						erroreventocola.getCoderror(), where, params);
			}
			if (erroreventocola.getTipoproc() != null) {
				UtilSQL.preparaCampoSQL("t1.TIPOPROC",
						erroreventocola.getTipoproc(), where, params);
			}
		}
		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}

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