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

/**
 * TipoOrganizacionDaoImpl.
 *  
 */
 
@Repository
@Transactional
public class TipoOrganizacionDaoImpl implements TipoOrganizacionDao {
    
    private static final String[] ORDER_BY_WHITE_LIST = new String[] {"ID_TIPOORGANIZACION", "DESCRIPCION", "DESCRIPCIONES"};
    
    private JdbcTemplate jdbcTemplate;
	
	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<TipoOrganizacion> rwMap = new RowMapper<TipoOrganizacion>() {
	    @Override
		public TipoOrganizacion mapRow(ResultSet resultSet, int rowNum) throws SQLException {
           return new TipoOrganizacion(
               resultSet.getLong("IDTIPOORGANIZACION"), resultSet.getString("DESCRIPCION"), resultSet.getString("DESCRIPCIONES")
           ); } } ;
           
	private RowMapper<TipoOrganizacion> rwMapPK = new RowMapper<TipoOrganizacion>() {
	    @Override
		public TipoOrganizacion mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new TipoOrganizacion(
				resultSet.getLong("IDTIPOORGANIZACION")
           ); } } ;

	/**
     * 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 TipoOrganizacion table.
     *
     * @param tipoorganizacion TipoOrganizacion
     * @return TipoOrganizacion
     */
    @Override
	public TipoOrganizacion add(TipoOrganizacion tipoorganizacion) {
    	StringBuilder query = new StringBuilder("INSERT INTO TIPO_ORGANIZACION (ID_TIPOORGANIZACION, DESCRIPCION, DESCRIPCIONES) VALUES (?,?,?)");
		this.jdbcTemplate.update(query.toString(), tipoorganizacion.getIdTipoorganizacion(), tipoorganizacion.getDescripcion(), tipoorganizacion.getDescripciones());
		return tipoorganizacion;
	}

    /**
     * Updates a single row in the TipoOrganizacion table.
     *
     * @param tipoorganizacion TipoOrganizacion
     * @return TipoOrganizacion
     */
    @Override
    public TipoOrganizacion update(TipoOrganizacion tipoorganizacion) {
		StringBuilder query = new StringBuilder("UPDATE TIPO_ORGANIZACION SET DESCRIPCION=?, DESCRIPCIONES=?");
		query.append(" WHERE ID_TIPOORGANIZACION=?");
		this.jdbcTemplate.update(query.toString(), tipoorganizacion.getDescripcion(), tipoorganizacion.getDescripciones(), tipoorganizacion.getIdTipoorganizacion());
		return tipoorganizacion;
	}

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

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

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

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

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

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

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

		if (tipoOrganizacion != null) {
			if (tipoOrganizacion.getIdTipoorganizacion() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_TIPOORGANIZACION", tipoOrganizacion.getIdTipoorganizacion());
			}
			if (tipoOrganizacion.getDescripcion() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESCRIPCION", tipoOrganizacion.getDescripcion());
			}
			if (tipoOrganizacion.getDescripciones() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.DESCRIPCIONES", tipoOrganizacion.getDescripciones());
			}
		}

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

		if (tipoOrganizacion != null) {
			if (tipoOrganizacion.getIdTipoorganizacion() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_TIPOORGANIZACION", tipoOrganizacion.getIdTipoorganizacion(), startsWith);
			}
			if (tipoOrganizacion.getDescripcion() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESCRIPCION", tipoOrganizacion.getDescripcion(), startsWith);
			}
			if (tipoOrganizacion.getDescripciones() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.DESCRIPCIONES", tipoOrganizacion.getDescripciones(), startsWith);
			}
		}

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

