package com.ejie.ab04b.dao.nora;

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

/**
 * PaisDaoImpl generated by UDA, 13-Jan-2017 12:55:52.
 * 
 * @author UDA
 */

@Repository()
@Transactional()
public class PaisDaoImpl implements PaisDao {

	private JdbcTemplate jdbcTemplate;

	private static final String QUERY_SELECT = "SELECT t1.ID ID, t1.DS_O DSO, t1.DS_C DSC, t1.DS_E DSE FROM PAIS t1 ";

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Pais> rwMap = new RowMapper<Pais>() {
		public Pais mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Pais(resultSet.getString("ID"),
					resultSet.getString("DSO"), resultSet.getString("DSC"),
					resultSet.getString("DSE"));
		}
	};

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

	/**
	 * 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
	 */

	/**
	 * Finds a single row in the Pais table.
	 * 
	 *  pais
	 *            Pais
	 *  Pais
	 *
	 * @param pais the pais
	 * @return the pais
	 */
	@Transactional(readOnly = true)
	public Pais find(Pais pais) {
		StringBuilder query = new StringBuilder(PaisDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID = ?");

		List<Pais> paisList = this.jdbcTemplate.query(query.toString(),
				this.rwMap, pais.getId());
		return (Pais) DataAccessUtils.uniqueResult(paisList);
	}

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

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

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

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

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

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

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

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(pais, 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 Pais selected for rup_table
	 * 
	 *  pais
	 *            Pais
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<TableRowDto<Pais>>.
	 *
	 * @param pais the pais
	 * @param jqGridRequestDto the jq grid request dto
	 * @param startsWith the starts with
	 * @return the list
	 */
	@Override()
	public List<TableRowDto<Pais>> reorderSelection(Pais pais,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(PaisDaoImpl.QUERY_SELECT);
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(pais, 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, Pais.class, filterParamList,
				"ID,DS_O,DS_C,DS_E");

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

	/**
	 * Search method for rup_table
	 * 
	 *  filterParams
	 *            Pais
	 *  searchParams
	 *            Pais
	 *  jqGridRequestDto
	 *            JQGridRequestDto
	 *  startsWith
	 *            Boolean
	 *  List<TableRowDto<Pais>>.
	 *
	 * @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<Pais>> search(Pais filterParams, Pais searchParams,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(PaisDaoImpl.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, Pais.class, filterParamList,
				searchSQL, searchParamList, from_alias, "ID,DS_O,DS_C,DS_E");

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

	/*
	 * MÉTODOS PRIVADOS
	 */

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

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

		if (pais != null && pais.getId() != null) {
			where.append(" AND t1.ID = ?");
			params.add(pais.getId());
		}
		if (pais != null && pais.getDsO() != null) {
			where.append(" AND t1.DS_O = ?");
			params.add(pais.getDsO());
		}
		if (pais != null && pais.getDsC() != null) {
			where.append(" AND t1.DS_C = ?");
			params.add(pais.getDsC());
		}
		if (pais != null && pais.getDsE() != null) {
			where.append(" AND t1.DS_E = ?");
			params.add(pais.getDsE());
		}

		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 Pais entity
	 * 
	 *  pais
	 *            Pais 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 pais the pais
	 * @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(Pais pais, Boolean startsWith) {

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

		if (pais != null && pais.getId() != null) {
			where.append(" AND UPPER(t1.ID) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(pais.getId().toUpperCase() + "%");
			} else {
				params.add("%" + pais.getId().toUpperCase() + "%");
			}
			where.append(" AND t1.ID IS NOT NULL");
		}
		if (pais != null && pais.getDsO() != null) {
			where.append(" AND UPPER(t1.DS_O) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(pais.getDsO().toUpperCase() + "%");
			} else {
				params.add("%" + pais.getDsO().toUpperCase() + "%");
			}
			where.append(" AND t1.DS_O IS NOT NULL");
		}
		if (pais != null && pais.getDsC() != null) {
			where.append(" AND UPPER(t1.DS_C) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(pais.getDsC().toUpperCase() + "%");
			} else {
				params.add("%" + pais.getDsC().toUpperCase() + "%");
			}
			where.append(" AND t1.DS_C IS NOT NULL");
		}
		if (pais != null && pais.getDsE() != null) {
			where.append(" AND UPPER(t1.DS_E) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(pais.getDsE().toUpperCase() + "%");
			} else {
				params.add("%" + pais.getDsE().toUpperCase() + "%");
			}
			where.append(" AND t1.DS_E 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;
}
