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

/**
 * EjeDaoImpl.
 *  
 */
 
@Repository
@Transactional
public class EjeDaoImpl implements EjeDao {
    
    private static final String[] ORDER_BY_WHITE_LIST = new String[] {"ID_EJE", "ORDEN", "PONDERACION", "ID_DECRETO", "ID_TIPOORGANIZACION", "NOMBRE", "NOMBRECAS", "HELBURU"};
    
    private JdbcTemplate jdbcTemplate;
	
	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Eje> rwMap = new RowMapper<Eje>() {
	    @Override
		public Eje mapRow(ResultSet resultSet, int rowNum) throws SQLException {
           return new Eje(
               resultSet.getLong("IDEJE"), resultSet.getLong("ORDEN"), resultSet.getLong("PONDERACION"), resultSet.getInt("IDDECRETO"), resultSet.getLong("IDTIPOORGANIZACION"), resultSet.getString("NOMBRE"), resultSet.getString("NOMBRECAS"), resultSet.getString("HELBURU")
           ); } } ;
           
	private RowMapper<Eje> rwMapPK = new RowMapper<Eje>() {
	    @Override
		public Eje mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Eje(
				resultSet.getLong("IDEJE")
           ); } } ;

	/**
     * 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 Eje table.
     *
     * @param eje Eje
     * @return Eje
     */
    @Override
	public Eje add(Eje eje) {
    	StringBuilder query = new StringBuilder("INSERT INTO EJE (ID_EJE, ORDEN, PONDERACION, ID_DECRETO, ID_TIPOORGANIZACION, NOMBRE, NOMBRECAS, HELBURU) VALUES (?,?,?,?,?,?,?,?)");
		this.jdbcTemplate.update(query.toString(), eje.getIdEje(), eje.getOrden(), eje.getPonderacion(), eje.getIdDecreto(), eje.getIdTipoorganizacion(), eje.getNombre(), eje.getNombrecas(), eje.getHelburu());
		return eje;
	}

    /**
     * Updates a single row in the Eje table.
     *
     * @param eje Eje
     * @return Eje
     */
    @Override
    public Eje update(Eje eje) {
		StringBuilder query = new StringBuilder("UPDATE EJE SET ORDEN=?, PONDERACION=?, ID_DECRETO=?, ID_TIPOORGANIZACION=?, NOMBRE=?, NOMBRECAS=?, HELBURU=?");
		query.append(" WHERE ID_EJE=?");
		this.jdbcTemplate.update(query.toString(), eje.getOrden(), eje.getPonderacion(), eje.getIdDecreto(), eje.getIdTipoorganizacion(), eje.getNombre(), eje.getNombrecas(), eje.getHelburu(), eje.getIdEje());
		return eje;
	}

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

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

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

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

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

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

	/**
	 * Remove multiple method for rup_table
     * 
     * @param filterEje Eje
     * @param jqGridRequestDto JQGridRequestDto
     * @param startsWith Boolean 
     */
	@Override
	public void removeMultiple(Eje filterEje, JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT - FROM
		/** TODO: select por clave */
		StringBuilder query = new StringBuilder(this.getSelectFromQuery(true));
		
		// WHERE
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterEje, 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, Eje.class, query, params, "IDEJE");
		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_EJE IDEJE, t1.ORDEN ORDEN, t1.PONDERACION PONDERACION, t1.ID_DECRETO IDDECRETO, t1.ID_TIPOORGANIZACION IDTIPOORGANIZACION, t1.NOMBRE NOMBRE, t1.NOMBRECAS NOMBRECAS, t1.HELBURU HELBURU ");
		if(includeFrom){
			query.append(" FROM EJE t1 ");
		}
		return query.toString();
	}
	 	
	/**
	 * Returns a map with the needed value to create the conditions to filter by 
	 * the Eje entity 
	 * 
	 * @param eje Eje
	 *            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 (Eje eje){
		
		StringBuilder where = new StringBuilder(Constants.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (eje != null) {
			if (eje.getIdEje() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_EJE", eje.getIdEje());
			}
			if (eje.getOrden() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ORDEN", eje.getOrden());
			}
			if (eje.getPonderacion() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.PONDERACION", eje.getPonderacion());
			}
			if (eje.getIdDecreto() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_DECRETO", eje.getIdDecreto());
			}
			if (eje.getIdTipoorganizacion() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.ID_TIPOORGANIZACION", eje.getIdTipoorganizacion());
			}
			if (eje.getNombre() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.NOMBRE", eje.getNombre());
			}
			if (eje.getNombrecas() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.NOMBRECAS", eje.getNombrecas());
			}
			if (eje.getHelburu() != null) {
				UtilSQL.createFilterSQL(where, params, "t1.HELBURU", eje.getHelburu());
			}
		}

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

		if (eje != null) {
			if (eje.getIdEje() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_EJE", eje.getIdEje(), startsWith);
			}
			if (eje.getOrden() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ORDEN", eje.getOrden(), startsWith);
			}
			if (eje.getPonderacion() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.PONDERACION", eje.getPonderacion(), startsWith);
			}
			if (eje.getIdDecreto() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_DECRETO", eje.getIdDecreto(), startsWith);
			}
			if (eje.getIdTipoorganizacion() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.ID_TIPOORGANIZACION", eje.getIdTipoorganizacion(), startsWith);
			}
			if (eje.getNombre() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.NOMBRE", eje.getNombre(), startsWith);
			}
			if (eje.getNombrecas() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.NOMBRECAS", eje.getNombrecas(), startsWith);
			}
			if (eje.getHelburu() != null) {
				UtilSQL.createFilterLikeSQL(where, params, "t1.HELBURU", eje.getHelburu(), startsWith);
			}
		}

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

