package com.ejie.ab39a.dao;

import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.TableRowDto;
import com.gfi.constants.Constants;
import com.gfi.utils.UtilSQL;
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.ab39a.model.Provincia;

/**
 * ProvinciaDaoImpl.
 * 
 *  
 */

@Repository
@Transactional
public class ProvinciaDaoImpl implements ProvinciaDao {

	private static final String[] ORDER_BY_WHITE_LIST = new String[] { "IDPROVINCIA", "DESCOF", "IDAUTONOMIA" };

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Provincia> rwMap = new RowMapper<Provincia>() {
		@Override
		public Provincia mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Provincia(resultSet.getString("IDPROVINCIA"), resultSet.getString("DESCOF"),
					resultSet.getString("IDAUTONOMIA"));
		}
	};

	private RowMapper<Provincia> rwMapPK = new RowMapper<Provincia>() {
		@Override
		public Provincia mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Provincia(resultSet.getString("IDPROVINCIA"), resultSet.getString("DESCOF"),
					resultSet.getString("IDAUTONOMIA"));
		}
	};

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

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the Provincia table.
	 *
	 * @param provincia
	 *            Provincia
	 * @return Provincia
	 */
	@Override
	public Provincia add(Provincia provincia) {
		StringBuilder query = new StringBuilder(
				"INSERT INTO PROVINCIA (ID_PROVINCIA, DESC_OF, ID_AUTONOMIA) VALUES (?,?,?)");
		this.jdbcTemplate.update(query.toString(), provincia.getIdProvincia(), provincia.getDescOf(),
				provincia.getIdAutonomia());
		return provincia;
	}

	/**
	 * Updates a single row in the Provincia table.
	 *
	 * @param provincia
	 *            Provincia
	 * @return Provincia
	 */
	@Override
	public Provincia update(Provincia provincia) {
		StringBuilder query = new StringBuilder("UPDATE PROVINCIA SET ");
		query.append(" WHERE ID_PROVINCIA=? AND DESC_OF=? AND ID_AUTONOMIA=?");
		this.jdbcTemplate.update(query.toString(), provincia.getIdProvincia(), provincia.getDescOf(),
				provincia.getIdAutonomia());
		return provincia;
	}

	/**
	 * Finds a single row in the Provincia table.
	 *
	 * @param provincia
	 *            Provincia
	 * @return Provincia
	 */
	@Override
	@Transactional(readOnly = true)
	public Provincia find(Provincia provincia) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
		// WHERE
		query.append(" WHERE t1.ID_PROVINCIA = ?   AND t1.DESC_OF = ?   AND t1.ID_AUTONOMIA = ?  ");

		List<Provincia> provinciaList = this.jdbcTemplate.query(query.toString(), this.rwMap,
				provincia.getIdProvincia(), provincia.getDescOf(), provincia.getIdAutonomia());
		return DataAccessUtils.uniqueResult(provinciaList);
	}

	/**
	 * Removes a single row in the Provincia table.
	 *
	 * @param provincia
	 *            Provincia
	 */
	@Override
	public void remove(Provincia provincia) {
		String query = "DELETE FROM PROVINCIA WHERE ID_PROVINCIA=? AND DESC_OF=? AND ID_AUTONOMIA=?";
		this.jdbcTemplate.update(query, provincia.getIdProvincia(), provincia.getDescOf(), provincia.getIdAutonomia());
	}

	/**
	 * Finds a list of rows in the Provincia table.
	 * 
	 * @param provincia
	 *            Provincia
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<Provincia>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Provincia> findAll(Provincia provincia, JQGridRequestDto jqGridRequestDto) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

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

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

	/**
	 * Finds a list of rows in the Provincia table.
	 * 
	 * @param provincia
	 *            Provincia
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<Provincia>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Provincia> findAllNavIp(Provincia provincia, JQGridRequestDto jqGridRequestDto) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(
				" SELECT t1.ID_PROVINCIA IDPROVINCIA, t1.DESC_OF DESCOF, t1.ID_AUTONOMIA IDAUTONOMIA"
						+ " FROM PROVINCIA t1 WHERE ID_AUTONOMIA = 16 UNION SELECT t1.ID_PROVINCIA IDPROVINCIA, t1.DESC_OF DESCOF, t1.ID_AUTONOMIA IDAUTONOMIA"
						+ " FROM PROVINCIA t1 WHERE ID_PROVINCIA =31 UNION SELECT '99' IDPROVINCIA,'Iparralde' DESCOF,'16' IDAUTONOMIA FROM DUAL ");

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

		return this.jdbcTemplate.query(query.toString(), this.rwMap);
	}

	/**
	 * Finds rows in the Provincia table using like.
	 * 
	 * @param provincia
	 *            Provincia
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<Provincia>
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Provincia> findAllLike(Provincia provincia, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Provincia table.
	 * 
	 * @param provincia
	 *            Provincia
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllCount(Provincia provincia) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM PROVINCIA t1 ");

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

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

		return this.jdbcTemplate.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Counts rows in the Provincia table using like.
	 * 
	 * @param provincia
	 *            Provincia
	 * @param startsWith
	 *            Boolean
	 * @return Long
	 */
	@Override
	@Transactional(readOnly = true)
	public Long findAllLikeCount(Provincia provincia, Boolean startsWith) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM PROVINCIA t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(provincia, 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.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Reorder the data list of Provincia selected for rup_table
	 * 
	 * @param provincia
	 *            Provincia
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<TableRowDto<Provincia>>
	 */
	@Override
	public List<TableRowDto<Provincia>> reorderSelection(Provincia provincia, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(provincia, 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, Provincia.class,
				filterParamList, "IDPROVINCIA, DESCOF, IDAUTONOMIA");

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

	/**
	 * Remove multiple method for rup_table
	 * 
	 * @param filterProvincia
	 *            Provincia
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 */
	@Override
	public void removeMultiple(Provincia filterProvincia, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		/** TODO: select por clave */
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// WHERE
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterProvincia, 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, Provincia.class,
				query, params, "IDPROVINCIA, DESCOF, IDAUTONOMIA");
		this.jdbcTemplate.update(sbRemoveMultipleSQL.toString(), params.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Devuelve la Select con todos los campos. Incluye el From si se indica.
	 * 
	 * @param includeFrom
	 *            boolean
	 * @return String
	 */
	private String getSelectFromQuery(boolean includeFrom) {
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_PROVINCIA IDPROVINCIA, t1.DESC_OF DESCOF, t1.ID_AUTONOMIA IDAUTONOMIA ");
		if (includeFrom) {
			query.append(" FROM PROVINCIA t1 ");
		}
		return query.toString();
	}

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

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

		if (provincia != null) {
			if (provincia.getIdProvincia() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_PROVINCIA", provincia.getIdProvincia());
			}
			if (provincia.getDescOf() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESC_OF", provincia.getDescOf());
			}
			if (provincia.getIdAutonomia() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_AUTONOMIA", provincia.getIdAutonomia());
			}
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Provincia entity
	 * 
	 * @param provincia
	 *            Provincia Bean with the criteria values to filter by.
	 * @param startsWith
	 *            Boolean
	 * @return 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.
	 */
	private Map<String, Object> getWhereLikeMap(Provincia provincia, Boolean startsWith) {

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

		if (provincia != null) {
			if (provincia.getIdProvincia() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_PROVINCIA", provincia.getIdProvincia(), startsWith);
			}
			if (provincia.getDescOf() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESC_OF", provincia.getDescOf(), startsWith);
			}
			if (provincia.getIdAutonomia() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_AUTONOMIA", provincia.getIdAutonomia(), startsWith);
			}
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}
}
