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.TiposReceptores;

/**
 * TiposReceptoresDaoImpl.
 *  
 */
 
@Repository
@Transactional
public class TiposReceptoresDaoImpl implements TiposReceptoresDao {
    
    private static final String[] ORDER_BY_WHITE_LIST = new String[] {"CODTIPORECEP", "DESCAS", "DESEUS"};
    
    private JdbcTemplate jdbcTemplate;
	
	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TiposReceptores> rwMap = new RowMapper<TiposReceptores>() {
	    @Override
		public TiposReceptores mapRow(ResultSet resultSet, int rowNum) throws SQLException {
           return new TiposReceptores(
               resultSet.getLong("CODTIPORECEP"), resultSet.getString("DESCAS"), resultSet.getString("DESEUS")
           ); } } ;
           
	private RowMapper<TiposReceptores> rwMapPK = new RowMapper<TiposReceptores>() {
	    @Override
		public TiposReceptores mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new TiposReceptores(
				resultSet.getLong("CODTIPORECEP")
           ); } } ;

	/**
     * 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 TiposReceptores table.
     *
     * @param tiposreceptores TiposReceptores
     * @return TiposReceptores
     */
    @Override
	public TiposReceptores add(TiposReceptores tiposreceptores) {
    	StringBuilder query = new StringBuilder("INSERT INTO TIPOS_RECEPTORES (CODTIPORECEP, DESCAS, DESEUS) VALUES (?,?,?)");
		this.jdbcTemplate.update(query.toString(), tiposreceptores.getCodtiporecep(), tiposreceptores.getDescas(), tiposreceptores.getDeseus());
		return tiposreceptores;
	}

    /**
     * Updates a single row in the TiposReceptores table.
     *
     * @param tiposreceptores TiposReceptores
     * @return TiposReceptores
     */
    @Override
    public TiposReceptores update(TiposReceptores tiposreceptores) {
		StringBuilder query = new StringBuilder("UPDATE TIPOS_RECEPTORES SET DESCAS=?, DESEUS=?");
		query.append(" WHERE CODTIPORECEP=?");
		this.jdbcTemplate.update(query.toString(), tiposreceptores.getDescas(), tiposreceptores.getDeseus(), tiposreceptores.getCodtiporecep());
		return tiposreceptores;
	}

    /**
     * Finds a single row in the TiposReceptores table.
     *
     * @param tiposreceptores TiposReceptores
     * @return TiposReceptores
     */
    @Override
    @Transactional (readOnly = true)
    public TiposReceptores find(TiposReceptores tiposreceptores) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
		// WHERE 
		query.append(" WHERE t1.CODTIPORECEP = ?  ");
		
		List<TiposReceptores> tiposreceptoresList = this.jdbcTemplate.query(query.toString(), this.rwMap, tiposreceptores.getCodtiporecep());
		return DataAccessUtils.uniqueResult(tiposreceptoresList);
    }

    /**
     * Removes a single row in the TiposReceptores table.
     *
     * @param tiposreceptores TiposReceptores
     */
    @Override
    public void remove(TiposReceptores tiposreceptores) {
		String query = "DELETE FROM TIPOS_RECEPTORES WHERE CODTIPORECEP=?";
		this.jdbcTemplate.update(query, tiposreceptores.getCodtiporecep());
    }
    
   /**
    * Finds a list of rows in the TiposReceptores table.
    * 
    * @param tiposReceptores TiposReceptores
    * @param jqGridRequestDto JQGridRequestDto
    * @return List<TiposReceptores> 
    */
    @Override
	@Transactional (readOnly = true)
    public List<TiposReceptores> findAll(TiposReceptores tiposReceptores, JQGridRequestDto jqGridRequestDto) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
		
		//Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(tiposReceptores); 
		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, TiposReceptoresDaoImpl.ORDER_BY_WHITE_LIST);
		}
		
		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}
	
	/**
	 * Finds rows in the TiposReceptores table using like.
     * 
     * @param tiposReceptores TiposReceptores
     * @param jqGridRequestDto JQGridRequestDto
     * @param startsWith Boolean
     * @return List<TiposReceptores>
     */
    @Override
	@Transactional (readOnly = true)
    public List<TiposReceptores> findAllLike(TiposReceptores tiposReceptores, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
      	
		//Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tiposReceptores,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, TiposReceptoresDaoImpl.ORDER_BY_WHITE_LIST);
		}
		
		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/*
	 * OPERACIONES RUP_TABLE
	 */
	
    /**
     * Counts rows in the TiposReceptores table.
     * 
     * @param tiposReceptores TiposReceptores
     * @return Long
     */
    @Override
    @Transactional (readOnly = true)
    public Long findAllCount(TiposReceptores tiposReceptores) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM TIPOS_RECEPTORES t1 ");
		
		//Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(tiposReceptores); 
		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 TiposReceptores table using like.
     * 
     * @param tiposReceptores TiposReceptores
     * @param startsWith Boolean
     * @return Long 
     */
    @Override 
	@Transactional (readOnly = true)
    public Long findAllLikeCount(TiposReceptores tiposReceptores, Boolean startsWith) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM TIPOS_RECEPTORES t1 ");

		//Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tiposReceptores,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 TiposReceptores selected for rup_table
     * 
     * @param tiposReceptores TiposReceptores
     * @param jqGridRequestDto JQGridRequestDto
     * @param startsWith Boolean
     * @return List<TableRowDto<TiposReceptores>> 
     */
	@Override 
	public List<TableRowDto<TiposReceptores>> reorderSelection(TiposReceptores tiposReceptores, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));

		// FILTRADO
		//Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(tiposReceptores,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, TiposReceptores.class, filterParamList, "CODTIPORECEP" );

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

	/**
	 * Remove multiple method for rup_table
     * 
     * @param filterTiposReceptores TiposReceptores
     * @param jqGridRequestDto JQGridRequestDto
     * @param startsWith Boolean 
     */
	@Override
	public void removeMultiple(TiposReceptores filterTiposReceptores, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		/** TODO: select por clave */
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
		
		// WHERE
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterTiposReceptores, 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, TiposReceptores.class, query, params, "CODTIPORECEP");
		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.CODTIPORECEP CODTIPORECEP, t1.DESCAS DESCAS, t1.DESEUS DESEUS ");
		if(includeFrom){
			query.append(" FROM TIPOS_RECEPTORES t1 ");
		}
		return query.toString();
	}
	 	
	/**
	 * Returns a map with the needed value to create the conditions to filter by 
	 * the TiposReceptores entity 
	 * 
	 * @param tiposReceptores TiposReceptores
	 *            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 (TiposReceptores tiposReceptores){
		
		StringBuilder where = new StringBuilder(Constants.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (tiposReceptores != null) {
			if (tiposReceptores.getCodtiporecep() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.CODTIPORECEP", tiposReceptores.getCodtiporecep());
			}
			if (tiposReceptores.getDescas() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESCAS", tiposReceptores.getDescas());
			}
			if (tiposReceptores.getDeseus() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESEUS", tiposReceptores.getDeseus());
			}
		}

		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 TiposReceptores entity 
	 * 
	 * @param tiposReceptores TiposReceptores
	 *            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 (TiposReceptores tiposReceptores, Boolean startsWith){
		
		StringBuilder where = new StringBuilder(Constants.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (tiposReceptores != null) {
			if (tiposReceptores.getCodtiporecep() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.CODTIPORECEP", tiposReceptores.getCodtiporecep(), startsWith);
			}
			if (tiposReceptores.getDescas() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESCAS", tiposReceptores.getDescas(), startsWith);
			}
			if (tiposReceptores.getDeseus() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESEUS", tiposReceptores.getDeseus(), startsWith);
			}
		}

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

