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

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

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

    /**
     * Updates a single row in the TiposIdentif table.
     *
     * @param tiposidentif TiposIdentif
     * @return TiposIdentif
     */
    @Override
    public TiposIdentif update(TiposIdentif tiposidentif) {
		StringBuilder query = new StringBuilder("UPDATE TIPOS_IDENTIF SET DESCAS=?, DESEUS=?");
		query.append(" WHERE CODIGO=?");
		this.jdbcTemplate.update(query.toString(), tiposidentif.getDescas(), tiposidentif.getDeseus(), tiposidentif.getCodigo());
		return tiposidentif;
	}

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

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

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

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

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

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

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

		if (tiposIdentif != null) {
			if (tiposIdentif.getCodigo() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.CODIGO", tiposIdentif.getCodigo());
			}
			if (tiposIdentif.getDescas() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESCAS", tiposIdentif.getDescas());
			}
			if (tiposIdentif.getDeseus() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESEUS", tiposIdentif.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 TiposIdentif entity 
	 * 
	 * @param tiposIdentif TiposIdentif
	 *            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 (TiposIdentif tiposIdentif, Boolean startsWith){
		
		StringBuilder where = new StringBuilder(Constants.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (tiposIdentif != null) {
			if (tiposIdentif.getCodigo() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.CODIGO", tiposIdentif.getCodigo(), startsWith);
			}
			if (tiposIdentif.getDescas() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESCAS", tiposIdentif.getDescas(), startsWith);
			}
			if (tiposIdentif.getDeseus() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESEUS", tiposIdentif.getDeseus(), startsWith);
			}
		}

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

