package com.ejie.ab04b.dao;

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.ab04b.constantes.Secuencias;
import com.ejie.ab04b.model.Tarea;
import com.ejie.ab04b.model.TareaOS3;
import com.ejie.ab04b.model.TramiteOS3;
import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * TareaOS3DaoImpl generated by UDA, 02-Feb-2017 13:49:16.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class TareaOS3DaoImpl implements TareaOS3Dao {

	private JdbcTemplate jdbcTemplate;

	private static final String QUERY_SELECT = "SELECT t1.ID_TAREA_096 IDTAREA096, t1.MAILBOX_TASK_ID_096 MAILBOXTASKID096, t1.TIPO_TAREA_096 TIPOTAREA096, t1.ESTADO_096 ESTADO096, t1.FECHA_INI_096 FECHAINI096, t1.FECHA_FIN_096 FECHAFIN096, t1.USUARIO_096 USUARIO096, t1.ID_TRAMITE_096 IDTRAMITE096 FROM AB0496S00 t1 ";

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TareaOS3> rwMap = new RowMapper<TareaOS3>() {
		public TareaOS3 mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new TareaOS3(resultSet.getLong("IDTAREA096"),
					resultSet.getString("MAILBOXTASKID096"),
					new Tarea(resultSet.getLong("TIPOTAREA096")),
					resultSet.getLong("ESTADO096"),
					resultSet.getTimestamp("FECHAINI096"),
					resultSet.getTimestamp("FECHAFIN096"),
					resultSet.getString("USUARIO096"),
					new TramiteOS3(resultSet.getLong("IDTRAMITE096")));
		}
	};

	private RowMapper<TareaOS3> rwMapPK = new RowMapper<TareaOS3>() {
		public TareaOS3 mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new TareaOS3(resultSet.getLong("IDTAREA096"));
		}
	};

	/**
	 * Gets the jdbc template.
	 * 
	 *  JdbcTemplate
	 *
	 * @return the jdbc template
	 */
	public JdbcTemplate getJdbcTemplate() {
		return this.jdbcTemplate;
	}

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

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the TareaOS3 table.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  TareaOS3
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @return the tarea OS 3
	 */
	public TareaOS3 add(TareaOS3 tareaOS3) {
		String query = "INSERT INTO AB0496S00 (ID_TAREA_096, ID_TRAMITE_096, MAILBOX_TASK_ID_096, TIPO_TAREA_096, ESTADO_096, FECHA_INI_096, FECHA_FIN_096, USUARIO_096) VALUES (?,?,?,?,?,?,?,?)";

		// Obtiene el trámite relacionado
		Long getTramiteOS3IdTramite095Aux = null;
		if (tareaOS3.getTramiteOS3() != null
				&& tareaOS3.getTramiteOS3().getIdTramite095() != null) {
			getTramiteOS3IdTramite095Aux = tareaOS3.getTramiteOS3()
					.getIdTramite095();
		}

		// Obtenemos la secuencia
		tareaOS3.setIdTarea096(
				Secuencias.TAREA_OS3.getNextLong(this.jdbcTemplate));

		this.jdbcTemplate.update(query, tareaOS3.getIdTarea096(),
				getTramiteOS3IdTramite095Aux, tareaOS3.getMailboxTaskId096(),
				tareaOS3.getTipoTarea().getIdTarea090(),
				tareaOS3.getEstado096(), tareaOS3.getFechaIni096(),
				tareaOS3.getFechaFin096(), tareaOS3.getUsuario096());
		return tareaOS3;
	}

	/**
	 * Updates a single row in the TareaOS3 table.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  TareaOS3
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @return the tarea OS 3
	 */
	public TareaOS3 update(TareaOS3 tareaOS3) {
		String query = "UPDATE AB0496S00 SET ID_TRAMITE_096=?, MAILBOX_TASK_ID_096=?, TIPO_TAREA_096=?, ESTADO_096=?, FECHA_INI_096=?, FECHA_FIN_096=?, USUARIO_096=? WHERE ID_TAREA_096=?";
		Object getTramiteOS3IdTramite095Aux = null;
		if (tareaOS3.getTramiteOS3() != null
				&& tareaOS3.getTramiteOS3().getIdTramite095() != null) {
			getTramiteOS3IdTramite095Aux = tareaOS3.getTramiteOS3()
					.getIdTramite095();
		}
		this.jdbcTemplate.update(query, getTramiteOS3IdTramite095Aux,
				tareaOS3.getMailboxTaskId096(),
				tareaOS3.getTipoTarea().getIdTarea090(),
				tareaOS3.getEstado096(), tareaOS3.getFechaIni096(),
				tareaOS3.getFechaFin096(), tareaOS3.getUsuario096(),
				tareaOS3.getIdTarea096());
		return tareaOS3;
	}

	/**
	 * Updates a single row in the Expedientes table.
	 * 
	 *  tarea
	 *            TareaOS3
	 *  TareaOS3
	 *
	 * @param tarea the tarea
	 * @return the tarea OS 3
	 */
	public TareaOS3 updateFilled(TareaOS3 tarea) {
		StringBuilder query = new StringBuilder("UPDATE AB0496S00 SET ");

		List<Object> params = new ArrayList<Object>();
		StringBuilder queryFields = new StringBuilder();

		if (tarea != null) {

			if (tarea.getUsuario096() != null) {
				queryFields.append(", USUARIO_096 = ? ");
				params.add(tarea.getUsuario096());
			}
			if (tarea.getFechaFin096() != null) {
				queryFields.append(", FECHA_FIN_096 = ? ");
				params.add(tarea.getFechaFin096());
			}
			if (tarea.getEstado096() != null) {
				queryFields.append(", ESTADO_096 = ? ");
				params.add(tarea.getEstado096());
			}

			if (queryFields.length() > 0) {
				queryFields.deleteCharAt(0);
			}
		}

		query.append(queryFields);
		query.append(" WHERE ID_TAREA_096 = ?");

		params.add(tarea.getIdTarea096());

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

	/**
	 * Finds a single row in the TareaOS3 table.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  TareaOS3
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @return the tarea OS 3
	 */
	@Transactional(readOnly = true)
	public TareaOS3 find(TareaOS3 tareaOS3) {
		StringBuilder query = new StringBuilder(TareaOS3DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_096 = ? ");

		List<TareaOS3> tareaOS3List = this.jdbcTemplate.query(query.toString(),
				this.rwMap, tareaOS3.getIdTarea096());
		return (TareaOS3) DataAccessUtils.uniqueResult(tareaOS3List);
	}

	/**
	 * Finds a single row in the TareaOS3 table.
	 * 
	 *  mailboxTaskId
	 *            String
	 *  TareaOS3
	 *
	 * @param mailboxTaskId the mailbox task id
	 * @return the tarea OS 3
	 */
	@Transactional(readOnly = true)
	public TareaOS3 findByMailboxTaskId(String mailboxTaskId) {
		StringBuilder query = new StringBuilder(TareaOS3DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.MAILBOX_TASK_ID_096 = ? ");

		List<TareaOS3> tareaOS3List = this.jdbcTemplate.query(query.toString(),
				this.rwMap, mailboxTaskId);
		return (TareaOS3) DataAccessUtils.uniqueResult(tareaOS3List);
	}

	/**
	 * Removes a single row in the TareaOS3 table.
	 * 
	 *  tareaOS3            TareaOS3
	 *
	 * @param tareaOS3 the tarea OS 3
	 */
	public void remove(TareaOS3 tareaOS3) {
		String query = "DELETE FROM AB0496S00 WHERE ID_TAREA_096=?";
		this.jdbcTemplate.update(query, tareaOS3.getIdTarea096());
	}

	/**
	 * Finds a list of rows in the TareaOS3 table.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<TareaOS3>
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TareaOS3> findAll(TareaOS3 tareaOS3,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(TareaOS3DaoImpl.QUERY_SELECT);

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

	/**
	 * Finds rows in the TareaOS3 table using like.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<TareaOS3>
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TareaOS3> findAllLike(TareaOS3 tareaOS3,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(TareaOS3DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_096 = ? ");

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the TareaOS3 table.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  Long
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(TareaOS3 tareaOS3) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0496S00 t1 ");

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

	/**
	 * Counts rows in the TareaOS3 table using like.
	 * 
	 *  tareaOS3
	 *            TareaOS3
	 *  startsWith
	 *            Boolean
	 *  Long
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @param startsWith the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(TareaOS3 tareaOS3, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0496S00 t1 ");

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

	/**
	 * Reorder the data list of TareaOS3 selected for rup_table.
	 * 
	 *  tareaOS3            TareaOS3
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TareaOS3>>
	 *
	 * @param tareaOS3 the tarea OS 3
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TareaOS3>> reorderSelection(TareaOS3 tareaOS3,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(TareaOS3DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_096 = ? ");
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tareaOS3, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		// Parámetros de filtrado
		@SuppressWarnings(value = "unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhere.get("params");

		// SQL para la reordenación
		StringBuilder sbReorderSelectionSQL = JQGridManager.getReorderQuery(
				query, jqGridRequestDto, TareaOS3.class, filterParamList,
				"ID_TAREA_096");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            TareaOS3
	 *  searchParams            TareaOS3
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TareaOS3>>
	 *
	 * @param filterParams the filter params
	 * @param searchParams the search params
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TareaOS3>> search(TareaOS3 filterParams,
			TareaOS3 searchParams, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(TareaOS3DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_096 = ? ");
		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");
		from_alias.add(" t2 ");

		// FILTRADO
		Map<String, ?> mapaWhereFilter = this.getWhereLikeMap(filterParams,
				startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhereFilter.get("query"));
		query.append(where);
		// Filter params
		@SuppressWarnings(value = "unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhereFilter
				.get("params");

		// BUSQUEDA
		Map<String, Object> mapaWhereSearch = this.getWhereLikeMap(searchParams,
				startsWith);
		String searchSQL = ((StringBuilder) mapaWhereSearch.get("query"))
				.toString();
		// Search params
		@SuppressWarnings(value = "unchecked")
		List<Object> searchParamList = (List<Object>) mapaWhereSearch
				.get("params");

		// SQL
		StringBuilder sbReorderSelectionSQL = JQGridManager.getSearchQuery(
				query, jqGridRequestDto, TareaOS3.class, filterParamList,
				searchSQL, searchParamList, from_alias, "ID_TAREA_096");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the TareaOS3 entity.
	 * 
	 *  tareaOS3            TareaOS3 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 tareaOS3 the tarea OS 3
	 * @return the where map
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereMap(TareaOS3 tareaOS3) {

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

		if (tareaOS3 != null && tareaOS3.getIdTarea096() != null) {
			where.append(" AND t1.ID_TAREA_096 = ?");
			params.add(tareaOS3.getIdTarea096());
		}
		if (tareaOS3 != null && tareaOS3.getTramiteOS3() != null
				&& tareaOS3.getTramiteOS3().getIdTramite095() != null) {
			where.append(" AND t1.ID_TRAMITE_096 = ?");
			params.add(tareaOS3.getTramiteOS3().getIdTramite095());
		}
		if (tareaOS3 != null && tareaOS3.getMailboxTaskId096() != null) {
			where.append(" AND t1.MAILBOX_TASK_ID_096 = ?");
			params.add(tareaOS3.getMailboxTaskId096());
		}
		if (tareaOS3 != null && tareaOS3.getTipoTarea() != null
				&& tareaOS3.getTipoTarea().getIdTarea090() != null) {
			where.append(" AND t1.TIPO_TAREA_096 = ?");
			params.add(tareaOS3.getTipoTarea().getIdTarea090());
		}
		if (tareaOS3 != null && tareaOS3.getEstado096() != null) {
			where.append(" AND t1.ESTADO_096 = ?");
			params.add(tareaOS3.getEstado096());
		}
		if (tareaOS3 != null && tareaOS3.getFechaIni096() != null) {
			where.append(" AND t1.FECHA_INI_096 = ?");
			params.add(tareaOS3.getFechaIni096());
		}
		if (tareaOS3 != null && tareaOS3.getFechaFin096() != null) {
			where.append(" AND t1.FECHA_FIN_096 = ?");
			params.add(tareaOS3.getFechaFin096());
		}
		if (tareaOS3 != null && tareaOS3.getUsuario096() != null) {
			where.append(" AND t1.USUARIO_096 = ?");
			params.add(tareaOS3.getUsuario096());
		}

		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 TareaOS3 entity.
	 * 
	 *  tareaOS3            TareaOS3 Bean with the criteria values to filter by.
	 *  startsWith            Boolean
	 *  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 tareaOS3 the tarea OS 3
	 * @param startsWith the starts with
	 * @return the where like map
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, Object> getWhereLikeMap(TareaOS3 tareaOS3,
			Boolean startsWith) {

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

		if (tareaOS3 != null && tareaOS3.getIdTarea096() != null) {
			where.append(" AND t1.ID_TAREA_096 = ?");
			params.add(tareaOS3.getIdTarea096());
		}
		if (tareaOS3 != null && tareaOS3.getTramiteOS3() != null
				&& tareaOS3.getTramiteOS3().getIdTramite095() != null) {
			where.append(" AND t1.ID_TRAMITE_096 = ?");
			params.add(tareaOS3.getTramiteOS3().getIdTramite095());
		}
		if (tareaOS3 != null && tareaOS3.getMailboxTaskId096() != null) {
			where.append(
					" AND UPPER(t1.MAILBOX_TASK_ID_096) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tareaOS3.getMailboxTaskId096().toUpperCase() + "%");
			} else {
				params.add("%" + tareaOS3.getMailboxTaskId096().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.MAILBOX_TASK_ID_096 IS NOT NULL");
		}
		if (tareaOS3 != null && tareaOS3.getTipoTarea() != null
				&& tareaOS3.getTipoTarea().getIdTarea090() != null) {
			where.append(" AND t1.TIPO_TAREA_096 = ?");
			params.add(tareaOS3.getTipoTarea().getIdTarea090());
		}
		if (tareaOS3 != null && tareaOS3.getEstado096() != null) {
			where.append(" AND t1.ESTADO_096 = ?");
			params.add(tareaOS3.getEstado096());
		}
		if (tareaOS3 != null && tareaOS3.getFechaIni096() != null) {
			where.append(" AND t1.FECHA_INI_096 = ?");
			params.add(tareaOS3.getFechaIni096());
		}
		if (tareaOS3 != null && tareaOS3.getFechaFin096() != null) {
			where.append(" AND t1.FECHA_FIN_096 = ?");
			params.add(tareaOS3.getFechaFin096());
		}
		if (tareaOS3 != null && tareaOS3.getUsuario096() != null) {
			where.append(" AND UPPER(t1.USUARIO_096) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tareaOS3.getUsuario096().toUpperCase() + "%");
			} else {
				params.add("%" + tareaOS3.getUsuario096().toUpperCase() + "%");
			}
			where.append(" AND t1.USUARIO_096 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;
}
