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.TareaOS2;
import com.ejie.ab04b.model.TramiteOS2;
import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;

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

@Repository()
@Transactional()
public class TareaOS2DaoImpl implements TareaOS2Dao {

	private JdbcTemplate jdbcTemplate;

	private static final String QUERY_SELECT = "SELECT t1.ID_TAREA_093 IDTAREA093, t1.MAILBOX_TASK_ID_093 MAILBOXTASKID093, t1.TIPO_TAREA_093 TIPOTAREA093, t1.ESTADO_093 ESTADO093, t1.FECHA_INI_093 FECHAINI093, t1.FECHA_FIN_093 FECHAFIN093, t1.USUARIO_093 USUARIO093, t1.ID_TRAMITE_093 IDTRAMITE093 FROM AB0493S00 t1 ";

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TareaOS2> rwMap = new RowMapper<TareaOS2>() {
		public TareaOS2 mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new TareaOS2(resultSet.getLong("IDTAREA093"),
					resultSet.getString("MAILBOXTASKID093"),
					new Tarea(resultSet.getLong("TIPOTAREA093")),
					resultSet.getLong("ESTADO093"),
					resultSet.getTimestamp("FECHAINI093"),
					resultSet.getTimestamp("FECHAFIN093"),
					resultSet.getString("USUARIO093"),
					new TramiteOS2(resultSet.getLong("IDTRAMITE093")));
		}
	};

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

	/**
	 * 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 TareaOS2 table.
	 * 
	 *  tareaOs2
	 *            TareaOS2
	 *  TareaOS2
	 *
	 * @param tareaOs2 the tarea os 2
	 * @return the tarea OS 2
	 */
	public TareaOS2 add(TareaOS2 tareaOs2) {
		String query = "INSERT INTO AB0493S00 (ID_TAREA_093, ID_TRAMITE_093, MAILBOX_TASK_ID_093, TIPO_TAREA_093, ESTADO_093, FECHA_INI_093, FECHA_FIN_093, USUARIO_093) VALUES (?,?,?,?,?,?,?,?)";

		// Obtiene el trámite relacionado
		Long getTramiteOS2IdTramite092Aux = null;
		if (tareaOs2.getTramiteOS2() != null
				&& tareaOs2.getTramiteOS2().getIdTramite092() != null) {
			getTramiteOS2IdTramite092Aux = tareaOs2.getTramiteOS2()
					.getIdTramite092();
		}

		// Obtenemos la secuencia
		tareaOs2.setIdTarea093(
				Secuencias.TAREA_OS2.getNextLong(this.jdbcTemplate));

		this.jdbcTemplate.update(query, tareaOs2.getIdTarea093(),
				getTramiteOS2IdTramite092Aux, tareaOs2.getMailboxTaskId093(),
				tareaOs2.getTipoTarea().getIdTarea090(),
				tareaOs2.getEstado093(), tareaOs2.getFechaIni093(),
				tareaOs2.getFechaFin093(), tareaOs2.getUsuario093());
		return tareaOs2;
	}

	/**
	 * Updates a single row in the TareaOS2 table.
	 * 
	 *  tareaOs2
	 *            TareaOS2
	 *  TareaOS2
	 *
	 * @param tareaOs2 the tarea os 2
	 * @return the tarea OS 2
	 */
	public TareaOS2 update(TareaOS2 tareaOs2) {
		String query = "UPDATE AB0493S00 SET ID_TRAMITE_093=?, MAILBOX_TASK_ID_093=?, TIPO_TAREA_093=?, ESTADO_093=?, FECHA_INI_093=?, FECHA_FIN_093=?, USUARIO_093=? WHERE ID_TAREA_093=?";
		Object getTramiteOS2IdTramite092Aux = null;
		if (tareaOs2.getTramiteOS2() != null
				&& tareaOs2.getTramiteOS2().getIdTramite092() != null) {
			getTramiteOS2IdTramite092Aux = tareaOs2.getTramiteOS2()
					.getIdTramite092();
		}
		this.jdbcTemplate.update(query, getTramiteOS2IdTramite092Aux,
				tareaOs2.getMailboxTaskId093(),
				tareaOs2.getTipoTarea().getIdTarea090(),
				tareaOs2.getEstado093(), tareaOs2.getFechaIni093(),
				tareaOs2.getFechaFin093(), tareaOs2.getUsuario093(),
				tareaOs2.getIdTarea093());
		return tareaOs2;
	}

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

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

		if (tarea != null) {

			if (tarea.getUsuario093() != null) {
				queryFields.append(", USUARIO_093 = ? ");
				params.add(tarea.getUsuario093());
			}
			if (tarea.getFechaFin093() != null) {
				queryFields.append(", FECHA_FIN_093 = ? ");
				params.add(tarea.getFechaFin093());
			}
			if (tarea.getEstado093() != null) {
				queryFields.append(", ESTADO_093 = ? ");
				params.add(tarea.getEstado093());
			}

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

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

		params.add(tarea.getIdTarea093());

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

	/**
	 * Finds a single row in the TareaOS2 table.
	 * 
	 *  tareaOs2
	 *            TareaOS2
	 *  TareaOS2
	 *
	 * @param tareaOs2 the tarea os 2
	 * @return the tarea OS 2
	 */
	@Transactional(readOnly = true)
	public TareaOS2 find(TareaOS2 tareaOs2) {
		StringBuilder query = new StringBuilder(TareaOS2DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_093 = ? ");

		List<TareaOS2> tareaOs2List = this.jdbcTemplate.query(query.toString(),
				this.rwMap, tareaOs2.getIdTarea093());
		return (TareaOS2) DataAccessUtils.uniqueResult(tareaOs2List);
	}

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

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

	/**
	 * Removes a single row in the TareaOS2 table.
	 * 
	 *  tareaOs2            TareaOS2
	 *
	 * @param tareaOs2 the tarea os 2
	 */
	public void remove(TareaOS2 tareaOs2) {
		String query = "DELETE FROM AB0493S00 WHERE ID_TAREA_093=?";
		this.jdbcTemplate.update(query, tareaOs2.getIdTarea093());
	}

	/**
	 * Finds a list of rows in the TareaOS2 table.
	 * 
	 *  tareaOs2
	 *            TareaOS2
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<TareaOS2>
	 *
	 * @param tareaOs2 the tarea os 2
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TareaOS2> findAll(TareaOS2 tareaOs2,
			JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(TareaOS2DaoImpl.QUERY_SELECT);

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

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the TareaOS2 table.
	 * 
	 *  tareaOs2
	 *            TareaOS2
	 *  Long
	 *
	 * @param tareaOs2 the tarea os 2
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(TareaOS2 tareaOs2) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0493S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(tareaOs2);
		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 TareaOS2 table using like.
	 * 
	 *  tareaOs2
	 *            TareaOS2
	 *  startsWith
	 *            Boolean
	 *  Long
	 *
	 * @param tareaOs2 the tarea os 2
	 * @param startsWith the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(TareaOS2 tareaOs2, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0493S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tareaOs2, 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 TareaOS2 selected for rup_table.
	 * 
	 *  tareaOs2            TareaOS2
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TareaOS2>>
	 *
	 * @param tareaOs2 the tarea os 2
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TareaOS2>> reorderSelection(TareaOS2 tareaOs2,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(TareaOS2DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_093 = ? ");
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tareaOs2, 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, TareaOS2.class, filterParamList,
				"ID_TAREA_093");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            TareaOS2
	 *  searchParams            TareaOS2
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TareaOS2>>
	 *
	 * @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<TareaOS2>> search(TareaOS2 filterParams,
			TareaOS2 searchParams, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(TareaOS2DaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_093 = ? ");
		// 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, TareaOS2.class, filterParamList,
				searchSQL, searchParamList, from_alias, "ID_TAREA_093");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (tareaOs2 != null && tareaOs2.getIdTarea093() != null) {
			where.append(" AND t1.ID_TAREA_093 = ?");
			params.add(tareaOs2.getIdTarea093());
		}
		if (tareaOs2 != null && tareaOs2.getTramiteOS2() != null
				&& tareaOs2.getTramiteOS2().getIdTramite092() != null) {
			where.append(" AND t1.ID_TRAMITE_093 = ?");
			params.add(tareaOs2.getTramiteOS2().getIdTramite092());
		}
		if (tareaOs2 != null && tareaOs2.getMailboxTaskId093() != null) {
			where.append(" AND t1.MAILBOX_TASK_ID_093 = ?");
			params.add(tareaOs2.getMailboxTaskId093());
		}
		if (tareaOs2 != null && tareaOs2.getTipoTarea() != null
				&& tareaOs2.getTipoTarea().getIdTarea090() != null) {
			where.append(" AND t1.TIPO_TAREA_093 = ?");
			params.add(tareaOs2.getTipoTarea().getIdTarea090());
		}
		if (tareaOs2 != null && tareaOs2.getEstado093() != null) {
			where.append(" AND t1.ESTADO_093 = ?");
			params.add(tareaOs2.getEstado093());
		}
		if (tareaOs2 != null && tareaOs2.getFechaIni093() != null) {
			where.append(" AND t1.FECHA_INI_093 = ?");
			params.add(tareaOs2.getFechaIni093());
		}
		if (tareaOs2 != null && tareaOs2.getFechaFin093() != null) {
			where.append(" AND t1.FECHA_FIN_093 = ?");
			params.add(tareaOs2.getFechaFin093());
		}
		if (tareaOs2 != null && tareaOs2.getUsuario093() != null) {
			where.append(" AND t1.USUARIO_093 = ?");
			params.add(tareaOs2.getUsuario093());
		}

		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 TareaOS2 entity.
	 * 
	 *  tareaOs2            TareaOS2 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 tareaOs2 the tarea os 2
	 * @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(TareaOS2 tareaOs2,
			Boolean startsWith) {

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

		if (tareaOs2 != null && tareaOs2.getIdTarea093() != null) {
			where.append(" AND t1.ID_TAREA_093 = ?");
			params.add(tareaOs2.getIdTarea093());
		}
		if (tareaOs2 != null && tareaOs2.getTramiteOS2() != null
				&& tareaOs2.getTramiteOS2().getIdTramite092() != null) {
			where.append(" AND t1.ID_TRAMITE_093 = ?");
			params.add(tareaOs2.getTramiteOS2().getIdTramite092());
		}
		if (tareaOs2 != null && tareaOs2.getMailboxTaskId093() != null) {
			where.append(
					" AND UPPER(t1.MAILBOX_TASK_ID_093) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tareaOs2.getMailboxTaskId093().toUpperCase() + "%");
			} else {
				params.add("%" + tareaOs2.getMailboxTaskId093().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.MAILBOX_TASK_ID_093 IS NOT NULL");
		}
		if (tareaOs2 != null && tareaOs2.getTipoTarea() != null
				&& tareaOs2.getTipoTarea().getIdTarea090() != null) {
			where.append(" AND t1.TIPO_TAREA_093 = ?");
			params.add(tareaOs2.getTipoTarea().getIdTarea090());
		}
		if (tareaOs2 != null && tareaOs2.getEstado093() != null) {
			where.append(" AND t1.ESTADO_093 = ?");
			params.add(tareaOs2.getEstado093());
		}
		if (tareaOs2 != null && tareaOs2.getFechaIni093() != null) {
			where.append(" AND t1.FECHA_INI_093 = ?");
			params.add(tareaOs2.getFechaIni093());
		}
		if (tareaOs2 != null && tareaOs2.getFechaFin093() != null) {
			where.append(" AND t1.FECHA_FIN_093 = ?");
			params.add(tareaOs2.getFechaFin093());
		}
		if (tareaOs2 != null && tareaOs2.getUsuario093() != null) {
			where.append(" AND UPPER(t1.USUARIO_093) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tareaOs2.getUsuario093().toUpperCase() + "%");
			} else {
				params.add("%" + tareaOs2.getUsuario093().toUpperCase() + "%");
			}
			where.append(" AND t1.USUARIO_093 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;
}
