package com.ejie.aa20b.dao;

import com.ejie.x38.dto.Pagination;
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.context.i18n.LocaleContextHolder;
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.aa20b.model.Clase;
import com.ejie.aa20b.util.Aa20bConstantes;

/**
 * ClaseDaoImpl generated by UDA, 28-nov-2014 11:32:16.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class ClaseDaoImpl implements ClaseDao {
	private JdbcTemplate jdbcTemplate;
	private RowMapper<Clase> rwMap = new RowMapper<Clase>() {
		public Clase mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Clase(resultSet.getInt("IDCLASE"),
					resultSet.getString("CCLASE"),
					resultSet.getString("ECLASE"), resultSet.getString("BAJA"),
					resultSet.getDate("FEINI"), resultSet.getString("USUPUBLI"));
		}
	};

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

	/**
	 * Inserts a single row in the Clase table.
	 * 
	 * @param clase
	 *            Pagination
	 * @return Clase
	 */
	public Clase add(Clase clase) {

		// Obtener el id correlativo
		Integer idCorrelativo = this.jdbcTemplate
				.queryForInt("SELECT CLASE_SEQ.NEXTVAL FROM DUAL");

		clase.setIdclase(idCorrelativo);
		String query = "INSERT INTO CLASE (IDCLASE, CCLASE, ECLASE, BAJA, FEINI, USUPUBLI) VALUES (?,?,?,?,?,?)";
		this.jdbcTemplate.update(query, clase.getIdclase(), clase.getCclase(),
				clase.getEclase(),
				clase.getBaja() == null ? "0" : clase.getBaja(),
				clase.getFeini(),
				clase.getUsupubli() == null ? "0" : clase.getUsupubli());
		return clase;
	}

	/**
	 * Updates a single row in the Clase table.
	 * 
	 * @param clase
	 *            Pagination
	 * @return Clase
	 */
	public Clase update(Clase clase) {
		String query = "UPDATE CLASE SET CCLASE=?, ECLASE=?, BAJA=?, FEINI=?, USUPUBLI=? WHERE IDCLASE=? ";
		this.jdbcTemplate.update(query, clase.getCclase(), clase.getEclase(),
				clase.getBaja() == null ? "0" : clase.getBaja(),
				clase.getFeini(),
				clase.getUsupubli() == null ? "0" : clase.getUsupubli(),
				clase.getIdclase());
		return clase;
	}

	/**
	 * Finds a single row in the Clase table.
	 * 
	 * @param clase
	 *            Pagination
	 * @return Clase
	 */
	@Transactional(readOnly = true)
	public Clase find(Clase clase) {
		String query = "SELECT t1.IDCLASE IDCLASE, t1.CCLASE CCLASE, t1.ECLASE ECLASE, t1.BAJA BAJA, t1.FEINI FEINI, t1.USUPUBLI USUPUBLI FROM CLASE t1  WHERE t1.IDCLASE = ? ";

		List<Clase> claseList = this.jdbcTemplate.query(query, this.rwMap,
				clase.getIdclase());
		return (Clase) DataAccessUtils.uniqueResult(claseList);
	}

	/**
	 * Devuelve true si la clase tiene la marca de Mostrar a usuario publico.
	 * 
	 * @param idClase
	 *            Integer
	 * @return Boolean
	 */
	public Boolean claseEsUsuPubli(Integer idClase) {
		String query = "SELECT t1.IDCLASE IDCLASE, t1.CCLASE CCLASE, t1.ECLASE ECLASE, t1.BAJA BAJA, t1.FEINI FEINI, t1.USUPUBLI USUPUBLI FROM CLASE t1  WHERE t1.IDCLASE = ? ";

		List<Clase> claseList = this.jdbcTemplate.query(query, this.rwMap,
				idClase);

		Clase clase = DataAccessUtils.uniqueResult(claseList);
		;
		if (clase.getUsupubli().equals("1")) {
			return true;
		} else {
			return false;
		}

	}

	/**
	 * Removes a single row in the Clase table.
	 * 
	 * @param clase
	 *            Pagination
	 * @return
	 */
	public void remove(Clase clase) {
		String query = "DELETE FROM CLASE WHERE IDCLASE=? AND CCLASE=? AND ECLASE=? AND BAJA=? AND FEINI=? AND USUPUBLI=?";
		this.jdbcTemplate.update(query, clase.getIdclase(), clase.getCclase(),
				clase.getEclase(), clase.getBaja(), clase.getFeini(),
				clase.getUsupubli());
	}

	/**
	 * Finds a List of rows in the Clase table.
	 * 
	 * @param clase
	 *            Clase
	 * @param pagination
	 *            Pagination
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Clase> findAll(Clase clase, Pagination pagination) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDCLASE IDCLASE,t1.CCLASE CCLASE,t1.ECLASE ECLASE,t1.BAJA BAJA,t1.FEINI FEINI, t1.USUPUBLI USUPUBLI ");
		query.append(" FROM CLASE t1 ");

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

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

		if (pagination != null) {
			query = pagination.getPaginationQuery(query);
		}

		return (List<Clase>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

	/**
	 * Clases asociadas y un servicio.
	 * 
	 * @param clase
	 *            Clase
	 * @param idServicio
	 *            Integer
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Clase> obtenerClasesServicio(Clase clase, Integer idServicio) {
		StringBuilder query = new StringBuilder(
				"SELECT DISTINCT t1.IDCLASE IDCLASE,t1.CCLASE CCLASE,t1.ECLASE ECLASE,t1.BAJA BAJA,t1.FEINI FEINI, t1.USUPUBLI USUPUBLI  ");

		if (idServicio != null && idServicio != 0) {
			query.append(" FROM CLASE t1, CODIGO t2 ");
		} else {
			query.append(" FROM CLASE t1 ");
		}

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMapServicio(clase, idServicio);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");

		where.append(mapaWhere.get("query"));
		query.append(where);

		if (LocaleContextHolder.getLocale().getLanguage()
				.equals(Aa20bConstantes.IDIOMA_EUSKERA))
			query.append(" ORDER BY t1.BAJA, t1.ECLASE");
		else
			query.append(" ORDER BY t1.BAJA, t1.CCLASE");

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

		return (List<Clase>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());

	}

	/**
	 * obtener las clases que esten en situación de Alta.
	 * 
	 * @param clase
	 *            Clase
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Clase> obtenerClasesAlta(Clase clase) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDCLASE IDCLASE,t1.CCLASE CCLASE,t1.ECLASE ECLASE,t1.BAJA BAJA,t1.FEINI FEINI, t1.USUPUBLI USUPUBLI ");
		query.append(" FROM CLASE t1 ");

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

		if (LocaleContextHolder.getLocale().getLanguage()
				.equals(Aa20bConstantes.IDIOMA_EUSKERA))
			query.append(" ORDER BY ECLASE");
		else
			query.append(" ORDER BY CCLASE");

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

		return (List<Clase>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

	/**
	 * obtener las clases que esten en situación de Alta asociadas a un
	 * servicio.
	 * 
	 * @param clase
	 *            Clase
	 * @param idServicio
	 *            Integer
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Clase> obtenerClasesAltaServicio(Clase clase, Integer idServicio) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDCLASE IDCLASE,t1.CCLASE CCLASE,t1.ECLASE ECLASE,t1.BAJA BAJA,t1.FEINI FEINI, t1.USUPUBLI USUPUBLI ");
		query.append(" FROM CLASE t1 ");

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

		if (LocaleContextHolder.getLocale().getLanguage()
				.equals(Aa20bConstantes.IDIOMA_EUSKERA))
			query.append(" ORDER BY ECLASE");
		else
			query.append(" ORDER BY CCLASE");

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

		return (List<Clase>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

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

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

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

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

	/**
	 * Finds rows in the Clase table using like.
	 * 
	 * @param clase
	 *            Clase
	 * @param pagination
	 *            Pagination
	 * @param startsWith
	 *            Boolean
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Clase> findAllLike(Clase clase, Pagination pagination,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDCLASE IDCLASE,t1.CCLASE CCLASE,t1.ECLASE ECLASE,t1.BAJA BAJA,t1.FEINI FEINI, t1.USUPUBLI USUPUBLI ");
		query.append(" FROM CLASE t1 ");

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

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

		if (pagination != null) {
			query = pagination.getPaginationQuery(query);
		}

		return (List<Clase>) this.jdbcTemplate.query(query.toString(),
				this.rwMap, params.toArray());
	}

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

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

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Clase entity
	 * 
	 * @param clase
	 *            Clase 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(Clase clase) {

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

		if (clase != null && clase.getIdclase() != null) {
			where.append(" AND t1.IDCLASE = ?");
			params.add(clase.getIdclase());
		}
		if (clase != null && clase.getCclase() != null) {
			where.append(" AND t1.CCLASE = ?");
			params.add(clase.getCclase());
		}
		if (clase != null && clase.getEclase() != null) {
			where.append(" AND t1.ECLASE = ?");
			params.add(clase.getEclase());
		}
		if (clase != null && clase.getBaja() != null) {
			where.append(" AND t1.BAJA = ?");
			params.add(clase.getBaja());
		}
		if (clase != null && clase.getFeini() != null) {
			where.append(" AND t1.FEINI = ?");
			params.add(clase.getFeini());
		}
		if (clase != null && clase.getUsupubli() != null) {
			where.append(" AND t1.USUPUBLI = ?");
			params.add(clase.getUsupubli());
		}

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

		return mapWhere;
	}

	private Map<String, ?> getWhereMapServicio(Clase clase, Integer idServicio) {

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

		if (idServicio != null && idServicio != 0) {
			where.append(" AND t1.IDCLASE=t2.IDCLASE AND t2.IDSERVICIO=? ");
			params.add(idServicio);
		}

		if (clase != null && clase.getIdclase() != null) {
			where.append(" AND t1.IDCLASE = ?");
			params.add(clase.getIdclase());
		}
		if (clase != null && clase.getCclase() != null) {
			where.append(" AND t1.CCLASE = ?");
			params.add(clase.getCclase());
		}
		if (clase != null && clase.getEclase() != null) {
			where.append(" AND t1.ECLASE = ?");
			params.add(clase.getEclase());
		}
		if (clase != null && clase.getBaja() != null) {
			where.append(" AND t1.BAJA = ?");
			params.add(clase.getBaja());
		}
		if (clase != null && clase.getFeini() != null) {
			where.append(" AND t1.FEINI = ?");
			params.add(clase.getFeini());
		}
		if (clase != null && clase.getUsupubli() != null) {
			where.append(" AND t1.USUPUBLI = ?");
			params.add(clase.getUsupubli());
		}

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

		return mapWhere;
	}

	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Clase entity
	 * 
	 * @param clase
	 *            Clase 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.
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereLikeMap(Clase clase, Boolean startsWith) {

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

		if (clase != null && clase.getIdclase() != null) {
			where.append(" AND t1.IDCLASE = ?");
			params.add(clase.getIdclase());
		}
		if (clase != null && clase.getCclase() != null) {
			where.append(" AND UPPER(t1.CCLASE) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(clase.getCclase().toUpperCase() + "%");
			} else {
				params.add("%" + clase.getCclase().toUpperCase() + "%");
			}
			where.append(" AND t1.CCLASE IS NOT NULL");
		}
		if (clase != null && clase.getEclase() != null) {
			where.append(" AND UPPER(t1.ECLASE) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(clase.getEclase().toUpperCase() + "%");
			} else {
				params.add("%" + clase.getEclase().toUpperCase() + "%");
			}
			where.append(" AND t1.ECLASE IS NOT NULL");
		}
		if (clase != null && clase.getBaja() != null) {
			where.append(" AND UPPER(t1.BAJA) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(clase.getBaja().toUpperCase() + "%");
			} else {
				params.add("%" + clase.getBaja().toUpperCase() + "%");
			}
			where.append(" AND t1.BAJA IS NOT NULL");
		}
		if (clase != null && clase.getFeini() != null) {
			where.append(" AND t1.FEINI = ?");
			params.add(clase.getFeini());
		}
		if (clase != null && clase.getUsupubli() != null) {
			where.append(" AND UPPER(t1.USUPUBLI) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(clase.getUsupubli().toUpperCase() + "%");
			} else {
				params.add("%" + clase.getUsupubli().toUpperCase() + "%");
			}
			where.append(" AND t1.USUPUBLI IS NOT NULL");
		}

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

		return mapWhere;
	}

	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

	/**
	 * StringBuilder initilization value
	 */
	public static final int STRING_BUILDER_INIT = 4096;
}
