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

/**
 * TipoObraDaoImpl generated by UDA, 11-Jan-2017 12:23:07.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class TipoObraDaoImpl implements TipoObraDao {

	private JdbcTemplate jdbcTemplate;

	private static final String QUERY_SELECT = "SELECT t1.TIPOBR_070 TIPOBR070, t1.DESOBR_EU_070 DESOBREU070, t1.DESOBR_ES_070 DESOBRES070, t1.FECBAJ_070 FECBAJ070, t1.DESOBRCOMP_EU_070 DESOBRCOMPEU070, t1.DESOBRCOMP_ES_070 DESOBRCOMPES070 FROM AB0470S00 t1 ";

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TipoObra> rwMap = new RowMapper<TipoObra>() {
		public TipoObra mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new TipoObra(resultSet.getString("TIPOBR070"), resultSet.getString("DESOBREU070"),
					resultSet.getString("DESOBRES070"), resultSet.getDate("FECBAJ070"),
					resultSet.getString("DESOBRCOMPEU070"), resultSet.getString("DESOBRCOMPES070"));
		}
	};

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

	/**
	 * 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 Ab04b70s00 table.
	 * 
	 *  tipoObra
	 *            TipoObra
	 *  TipoObra
	 *
	 * @param tipoObra the tipo obra
	 * @return the tipo obra
	 */
	public TipoObra add(TipoObra tipoObra) {
		
		Long tipoObraPK = Secuencias.TIPOS_OBRAS.getNextLong(this.jdbcTemplate);
		if (tipoObraPK != null) {
			tipoObra.setTipobr070(tipoObraPK.toString());
		}
		
		String query = "INSERT INTO AB0470S00 (TIPOBR_070, DESOBR_EU_070, DESOBR_ES_070, FECBAJ_070, DESOBRCOMP_EU_070, DESOBRCOMP_ES_070) VALUES (?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, tipoObra.getTipobr070(), tipoObra.getDesobrEu070(),
				tipoObra.getDesobrEs070(), tipoObra.getFecbaj070(), tipoObra.getDesobrcompEu070(),
				tipoObra.getDesobrcompEs070());
		return tipoObra;
	}

	/**
	 * Updates a single row in the Ab04b70s00 table.
	 * 
	 *  tipoObra
	 *            TipoObra
	 *  TipoObra
	 *
	 * @param tipoObra the tipo obra
	 * @return the tipo obra
	 */
	public TipoObra update(TipoObra tipoObra) {
		String query = "UPDATE AB0470S00 SET DESOBR_EU_070 = ?, DESOBR_ES_070 = ?, FECBAJ_070 = ?, DESOBRCOMP_EU_070 = ?, DESOBRCOMP_ES_070 = ? WHERE TIPOBR_070=?";
		this.jdbcTemplate.update(query, tipoObra.getDesobrEu070(), tipoObra.getDesobrEs070(),
				tipoObra.getFecbaj070(), tipoObra.getDesobrcompEu070(), tipoObra.getDesobrcompEs070(),
				tipoObra.getTipobr070());
		return tipoObra;
	}

	/**
	 * Finds a single row in the Ab04b70s00 table.
	 * 
	 *  tipoObra
	 *            TipoObra
	 *  TipoObra
	 *
	 * @param tipoObra the tipo obra
	 * @return the tipo obra
	 */
	@Transactional(readOnly = true)
	public TipoObra find(TipoObra tipoObra) {
		StringBuilder query = new StringBuilder(TipoObraDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.TIPOBR_070 = ? ");

		List<TipoObra> tipoObraList = this.jdbcTemplate.query(query.toString(), this.rwMap, tipoObra.getTipobr070());
		return (TipoObra) DataAccessUtils.uniqueResult(tipoObraList);
	}

	/**
	 * Removes a single row in the Ab04b70s00 table.
	 * 
	 *  tipoObra            TipoObra
	 *
	 * @param tipoObra the tipo obra
	 */
	public void remove(TipoObra tipoObra) {
		String query = "DELETE FROM AB0470S00 WHERE TIPOBR_070=? ";
		this.jdbcTemplate.update(query, tipoObra.getTipobr070());
	}

	/**
	 * Finds a list of rows in the Ab04b70s00 table.
	 * 
	 *  tipoObra
	 *            TipoObra
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<TipoObra>
	 *
	 * @param tipoObra the tipo obra
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TipoObra> findAll(TipoObra tipoObra, JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(TipoObraDaoImpl.QUERY_SELECT);

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

	/**
	 * Finds rows in the Ab04b70s00 table using like.
	 * 
	 *  tipoObra
	 *            TipoObra
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<TipoObra>
	 *
	 * @param tipoObra the tipo obra
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<TipoObra> findAllLike(TipoObra tipoObra, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(TipoObraDaoImpl.QUERY_SELECT);

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab04b70s00 table.
	 * 
	 *  tipoObra
	 *            TipoObra
	 *  Long
	 *
	 * @param tipoObra the tipo obra
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(TipoObra tipoObra) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM AB0470S00 t1 ");

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tipoObra, 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 Ab04b70s00 selected for rup_table.
	 * 
	 *  tipoObra            TipoObra
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TipoObra>>
	 *
	 * @param tipoObra the tipo obra
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<TipoObra>> reorderSelection(TipoObra tipoObra, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(TipoObraDaoImpl.QUERY_SELECT);
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tipoObra, 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, TipoObra.class,
				filterParamList,
				"TIPOBR_070");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            TipoObra
	 *  searchParams            TipoObra
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<TipoObra>>
	 *
	 * @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<TipoObra>> search(TipoObra filterParams, TipoObra searchParams,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(TipoObraDaoImpl.QUERY_SELECT);
		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");

		// 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, TipoObra.class,
				filterParamList, searchSQL, searchParamList, from_alias,
				"TIPOBR_070");

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

	/**
	 * Remove multiple method for rup_table.
	 * 
	 *  filterTipoObra            TipoObra
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *
	 * @param filterTipoObra the filter tipo obra
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 */
	@Override()
	public void removeMultiple(TipoObra filterTipoObra, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(TipoObraDaoImpl.QUERY_SELECT);
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterTipoObra, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		@SuppressWarnings(value = "unchecked")
		List<Object> params = (List<Object>) mapaWhere.get("params");

		StringBuilder sbRemoveMultipleSQL = JQGridManager.getRemoveMultipleQuery(jqGridRequestDto, TipoObra.class,
				query, params, "TIPOBR_070");
		this.jdbcTemplate.update(sbRemoveMultipleSQL.toString(), params.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (tipoObra != null && tipoObra.getTipobr070() != null) {
			where.append(" AND t1.TIPOBR_070 = ?");
			params.add(tipoObra.getTipobr070());
		}
		if (tipoObra != null && tipoObra.getDesobrEu070() != null) {
			where.append(" AND t1.DESOBR_EU_070 = ?");
			params.add(tipoObra.getDesobrEu070());
		}
		if (tipoObra != null && tipoObra.getDesobrEs070() != null) {
			where.append(" AND t1.DESOBR_ES_070 = ?");
			params.add(tipoObra.getDesobrEs070());
		}
		if (tipoObra != null && tipoObra.getDesobrcompEu070() != null) {
			where.append(" AND t1.DESOBRCOMP_EU_070 = ?");
			params.add(tipoObra.getDesobrcompEu070());
		}
		if (tipoObra != null && tipoObra.getDesobrcompEs070() != null) {
			where.append(" AND t1.DESOBRCOMP_ES_070 = ?");
			params.add(tipoObra.getDesobrcompEs070());
		}
		where.append(" AND (t1.FECBAJ_070 IS NULL OR t1.FECBAJ_070 > SYSDATE)");

		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 Ab04b70s00 entity.
	 * 
	 *  tipoObra            TipoObra 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 tipoObra the tipo obra
	 * @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(TipoObra tipoObra, Boolean startsWith) {

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

		if (tipoObra != null && tipoObra.getTipobr070() != null) {
			where.append(" AND UPPER(t1.TIPOBR_070) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tipoObra.getTipobr070().toUpperCase() + "%");
			} else {
				params.add("%" + tipoObra.getTipobr070().toUpperCase() + "%");
			}
			where.append(" AND t1.TIPOBR_070 IS NOT NULL");
		}
		if (tipoObra != null && tipoObra.getDesobrEu070() != null) {
			where.append(" AND UPPER(t1.DESOBR_EU_070) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tipoObra.getDesobrEu070().toUpperCase() + "%");
			} else {
				params.add("%" + tipoObra.getDesobrEu070().toUpperCase() + "%");
			}
			where.append(" AND t1.DESOBR_EU_070 IS NOT NULL");
		}
		if (tipoObra != null && tipoObra.getDesobrEs070() != null) {
			where.append(" AND UPPER(t1.DESOBR_ES_070) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tipoObra.getDesobrEs070().toUpperCase() + "%");
			} else {
				params.add("%" + tipoObra.getDesobrEs070().toUpperCase() + "%");
			}
			where.append(" AND t1.DESOBR_ES_070 IS NOT NULL");
		}
		if (tipoObra != null && tipoObra.getDesobrcompEu070() != null) {
			where.append(" AND UPPER(t1.DESOBRCOMP_EU_070) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tipoObra.getDesobrcompEu070().toUpperCase() + "%");
			} else {
				params.add("%" + tipoObra.getDesobrcompEu070().toUpperCase() + "%");
			}
			where.append(" AND t1.DESOBRCOMP_EU_070 IS NOT NULL");
		}
		if (tipoObra != null && tipoObra.getDesobrcompEs070() != null) {
			where.append(" AND UPPER(t1.DESOBRCOMP_ES_070) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(tipoObra.getDesobrcompEs070().toUpperCase() + "%");
			} else {
				params.add("%" + tipoObra.getDesobrcompEs070().toUpperCase() + "%");
			}
			where.append(" AND t1.DESOBRCOMP_ES_070 IS NOT NULL");
		}
		
		if (tipoObra != null && tipoObra.getFecbajaDesde() != null) {
			where.append(" AND t1.FECBAJ_070 >= ?");
			params.add(tipoObra.getFecbajaDesde());
		}
		if (tipoObra != null && tipoObra.getFecbajaHasta() != null) {
			where.append(" AND t1.FECBAJ_070 <= ?");
			params.add(tipoObra.getFecbajaHasta());
		}
		if(tipoObra != null && tipoObra.getFecbajaDesde() == null && tipoObra.getFecbajaHasta() == null){
			where.append(" AND (t1.FECBAJ_070 IS NULL OR t1.FECBAJ_070 > SYSDATE)");
		}
		
		//where.append(" AND (t1.FECBAJ_070 IS NULL OR t1.FECBAJ_070 > SYSDATE)");

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