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

/**
 * Ab0476s00DaoImpl generated by UDA, 07-Feb-2017 13:06:25.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class BuzonDaoImpl implements BuzonDao {
	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Buzon> rwMap = new RowMapper<Buzon>() {
		public Buzon mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Buzon(GrupoBuzon.valueOf(resultSet.getString("CODGRUPO076")),
					resultSet.getString("CODTERRIT076"), resultSet.getString("DESCRIPCION076"),
					resultSet.getString("MAILBOX076"));
		}
	};

	private RowMapper<Buzon> rwMapPK = new RowMapper<Buzon>() {
		public Buzon mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Buzon(GrupoBuzon.valueOf(resultSet.getString("CODGRUPO076")),
					resultSet.getString("CODTERRIT076"));
		}
	};

	/**
	 * 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 Ab0476s00 table.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  Ab0476s00
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @return the buzon
	 */
	public Buzon add(Buzon ab0476s00) {
		String query = "INSERT INTO AB0476S00 (COD_GRUPO_076, COD_TERRIT_076, DESCRIPCION_076, MAILBOX_076) VALUES (?,?,?,?)";
		this.jdbcTemplate.update(query, ab0476s00.getGrupo().name(), ab0476s00.getCodTerrit076(),
				ab0476s00.getDescripcion076(), ab0476s00.getMailbox076());
		return ab0476s00;
	}

	/**
	 * Updates a single row in the Ab0476s00 table.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  Ab0476s00
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @return the buzon
	 */
	public Buzon update(Buzon ab0476s00) {
		String query = "UPDATE AB0476S00 SET DESCRIPCION_076=?, MAILBOX_076=? WHERE COD_GRUPO_076=? AND COD_TERRIT_076=?";
		this.jdbcTemplate.update(query, ab0476s00.getDescripcion076(), ab0476s00.getMailbox076(),
				ab0476s00.getGrupo().name(), ab0476s00.getCodTerrit076());
		return ab0476s00;
	}

	/**
	 * Finds a single row in the Ab0476s00 table.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  Ab0476s00
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @return the buzon
	 */
	@Transactional(readOnly = true)
	public Buzon find(Buzon ab0476s00) {
		String query = "SELECT t1.COD_GRUPO_076 CODGRUPO076, t1.COD_TERRIT_076 CODTERRIT076, t1.DESCRIPCION_076 DESCRIPCION076, t1.MAILBOX_076 MAILBOX076 FROM AB0476S00 t1  WHERE t1.COD_GRUPO_076 = ?   AND t1.COD_TERRIT_076 = ?  ";

		List<Buzon> ab0476s00List = this.jdbcTemplate.query(query, this.rwMap, ab0476s00.getGrupo().name(),
				ab0476s00.getCodTerrit076());
		return (Buzon) DataAccessUtils.uniqueResult(ab0476s00List);
	}

	/**
	 * Removes a single row in the Ab0476s00 table.
	 * 
	 *  ab0476s00            Ab0476s00
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 */
	public void remove(Buzon ab0476s00) {
		String query = "DELETE FROM AB0476S00 WHERE COD_GRUPO_076=? AND COD_TERRIT_076=?";
		this.jdbcTemplate.update(query, ab0476s00.getGrupo().name(), ab0476s00.getCodTerrit076());
	}

	/**
	 * Finds a list of rows in the Ab0476s00 table.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  List<Ab0476s00>
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<Buzon> findAll(Buzon ab0476s00, JQGridRequestDto jqGridRequestDto) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.COD_GRUPO_076 CODGRUPO076,t1.COD_TERRIT_076 CODTERRIT076,t1.DESCRIPCION_076 DESCRIPCION076,t1.MAILBOX_076 MAILBOX076 ");
		query.append("FROM AB0476S00 t1 ");

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

	/**
	 * Finds rows in the Ab0476s00 table using like.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<Ab0476s00>
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<Buzon> findAllLike(Buzon ab0476s00, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.COD_GRUPO_076 CODGRUPO076,t1.COD_TERRIT_076 CODTERRIT076,t1.DESCRIPCION_076 DESCRIPCION076,t1.MAILBOX_076 MAILBOX076 ");
		query.append("FROM AB0476S00 t1 ");

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0476s00 table.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  Long
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Buzon ab0476s00) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM AB0476S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(ab0476s00);
		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 Ab0476s00 table using like.
	 * 
	 *  ab0476s00
	 *            Ab0476s00
	 *  startsWith
	 *            Boolean
	 *  Long
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @param startsWith the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(Buzon ab0476s00, Boolean startsWith) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM AB0476S00 t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0476s00, 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 Ab0476s00 selected for rup_table.
	 * 
	 *  ab0476s00            Ab0476s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0476s00>>
	 *
	 * @param ab0476s00 the ab 0476 s 00
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<Buzon>> reorderSelection(Buzon ab0476s00, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.COD_GRUPO_076 CODGRUPO076,t1.COD_TERRIT_076 CODTERRIT076,t1.DESCRIPCION_076 DESCRIPCION076,t1.MAILBOX_076 MAILBOX076 ");
		// FROM
		query.append("FROM AB0476S00 t1 ");
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(ab0476s00, 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, Buzon.class,
				filterParamList, "COD_GRUPO_076,COD_TERRIT_076");

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

	/**
	 * Search method for rup_table.
	 * 
	 *  filterParams            Ab0476s00
	 *  searchParams            Ab0476s00
	 *  jqGridRequestDto            JQGridRequestDto
	 *  startsWith            Boolean
	 *  List<TableRowDto<Ab0476s00>>
	 *
	 * @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<Buzon>> search(Buzon filterParams, Buzon searchParams, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.COD_GRUPO_076 CODGRUPO076,t1.COD_TERRIT_076 CODTERRIT076,t1.DESCRIPCION_076 DESCRIPCION076,t1.MAILBOX_076 MAILBOX076 ");
		// FROM
		query.append("FROM AB0476S00 t1 ");
		// 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, Buzon.class,
				filterParamList, searchSQL, searchParamList, from_alias, "COD_GRUPO_076,COD_TERRIT_076");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Ab0476s00 entity.
	 * 
	 *  ab0476s00            Ab0476s00 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 ab0476s00 the ab 0476 s 00
	 * @return the where map
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereMap(Buzon ab0476s00) {

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

		if (ab0476s00 != null && ab0476s00.getGrupo() != null) {
			where.append(" AND t1.COD_GRUPO_076 = ?");
			params.add(ab0476s00.getGrupo().name());
		}
		if (ab0476s00 != null && ab0476s00.getCodTerrit076() != null) {
			where.append(" AND t1.COD_TERRIT_076 = ?");
			params.add(ab0476s00.getCodTerrit076());
		}
		if (ab0476s00 != null && ab0476s00.getDescripcion076() != null) {
			where.append(" AND t1.DESCRIPCION_076 = ?");
			params.add(ab0476s00.getDescripcion076());
		}
		if (ab0476s00 != null && ab0476s00.getMailbox076() != null) {
			where.append(" AND t1.MAILBOX_076 = ?");
			params.add(ab0476s00.getMailbox076());
		}

		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 Ab0476s00 entity.
	 * 
	 *  ab0476s00            Ab0476s00 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 ab0476s00 the ab 0476 s 00
	 * @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(Buzon ab0476s00, Boolean startsWith) {

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

		if (ab0476s00 != null && ab0476s00.getGrupo() != null) {
			where.append(" AND UPPER(t1.COD_GRUPO_076) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0476s00.getGrupo().name() + "%");
			} else {
				params.add("%" + ab0476s00.getGrupo().name() + "%");
			}
			where.append(" AND t1.COD_GRUPO_076 IS NOT NULL");
		}
		if (ab0476s00 != null && ab0476s00.getCodTerrit076() != null) {
			where.append(" AND UPPER(t1.COD_TERRIT_076) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0476s00.getCodTerrit076().toUpperCase() + "%");
			} else {
				params.add("%" + ab0476s00.getCodTerrit076().toUpperCase() + "%");
			}
			where.append(" AND t1.COD_TERRIT_076 IS NOT NULL");
		}
		if (ab0476s00 != null && ab0476s00.getDescripcion076() != null) {
			where.append(" AND UPPER(t1.DESCRIPCION_076) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0476s00.getDescripcion076().toUpperCase() + "%");
			} else {
				params.add("%" + ab0476s00.getDescripcion076().toUpperCase() + "%");
			}
			where.append(" AND t1.DESCRIPCION_076 IS NOT NULL");
		}
		if (ab0476s00 != null && ab0476s00.getMailbox076() != null) {
			where.append(" AND UPPER(t1.MAILBOX_076) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0476s00.getMailbox076().toUpperCase() + "%");
			} else {
				params.add("%" + ab0476s00.getMailbox076().toUpperCase() + "%");
			}
			where.append(" AND t1.MAILBOX_076 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;
}
