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.Servicios;
import com.ejie.aa20b.util.Aa20bConstantes;

/**
 * ServiciosDaoImpl generated by UDA, 16-sep-2015 9:53:11.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class ServiciosDaoImpl implements ServiciosDao {
	private JdbcTemplate jdbcTemplate;
	private RowMapper<Servicios> rwMap = new RowMapper<Servicios>() {
		public Servicios mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new Servicios(resultSet.getLong("IDSERVICIO"),
					resultSet.getString("CSERVICIO"),
					resultSet.getString("ESERVICIO"),
					resultSet.getString("BAJA"));
		}
	};

	/**
	 * 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 Servicios table.
	 * 
	 * @param servicios
	 *            Pagination
	 * @return Servicios
	 */
	public Servicios add(Servicios servicios) {
		final Long nextId = this.jdbcTemplate
				.queryForLong("SELECT SERVICIOS_SEQ.NEXTVAL FROM DUAL");

		servicios.setIdservicio(nextId);

		String query = "INSERT INTO SERVICIOS (IDSERVICIO, CSERVICIO, ESERVICIO, BAJA) VALUES (?,?,?,?)";
		this.jdbcTemplate.update(query, servicios.getIdservicio(),
				servicios.getCservicio(), servicios.getEservicio(),
				servicios.getBaja() == null ? "0" : servicios.getBaja());
		return servicios;
	}

	/**
	 * Updates a single row in the Servicios table.
	 * 
	 * @param servicios
	 *            Pagination
	 * @return Servicios
	 */
	public Servicios update(Servicios servicios) {
		String query = "UPDATE SERVICIOS SET CSERVICIO=?, ESERVICIO=?, BAJA=? WHERE IDSERVICIO=?";
		this.jdbcTemplate.update(query, servicios.getCservicio(), servicios
				.getEservicio(),
				servicios.getBaja() == null ? "0" : servicios.getBaja(),
				servicios.getIdservicio());
		return servicios;
	}

	/**
	 * Finds a single row in the Servicios table.
	 * 
	 * @param servicios
	 *            Pagination
	 * @return Servicios
	 */
	@Transactional(readOnly = true)
	public Servicios find(Servicios servicios) {
		String query = "SELECT t1.IDSERVICIO IDSERVICIO, t1.CSERVICIO CSERVICIO, t1.ESERVICIO ESERVICIO, t1.BAJA BAJA FROM SERVICIOS t1  WHERE t1.IDSERVICIO = ?  ";

		List<Servicios> serviciosList = this.jdbcTemplate.query(query,
				this.rwMap, servicios.getIdservicio());
		return (Servicios) DataAccessUtils.uniqueResult(serviciosList);
	}

	/**
	 * Removes a single row in the Servicios table.
	 * 
	 * @param servicios
	 *            Pagination
	 * @return
	 */
	public void remove(Servicios servicios) {
		String query = "DELETE FROM SERVICIOS WHERE IDSERVICIO=?";
		this.jdbcTemplate.update(query, servicios.getIdservicio());
	}

	/**
	 * Finds a List of rows in the Servicios table.
	 * 
	 * @param servicios
	 *            Servicios
	 * @param pagination
	 *            Pagination
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Servicios> findAll(Servicios servicios, Pagination pagination) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDSERVICIO IDSERVICIO,t1.CSERVICIO CSERVICIO,t1.ESERVICIO ESERVICIO,t1.BAJA BAJA ");
		query.append("FROM SERVICIOS t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(servicios);
		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);
		} else {
			if (LocaleContextHolder.getLocale().getLanguage()
					.equals(Aa20bConstantes.IDIOMA_EUSKERA))
				query.append(" ORDER BY t1.BAJA, t1.ESERVICIO");
			else
				query.append(" ORDER BY t1.BAJA, t1.CSERVICIO");
		}

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

	/**
	 * Finds a List of rows in the Servicios table.
	 * 
	 * @param servicios
	 *            Servicios
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Servicios> obtenerServiciosNoCero(Servicios servicios) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDSERVICIO IDSERVICIO,t1.CSERVICIO CSERVICIO,t1.ESERVICIO ESERVICIO,t1.BAJA BAJA ");
		query.append("FROM SERVICIOS t1 ");

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

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

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

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

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(servicios);
		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 Servicios table using like.
	 * 
	 * @param servicios
	 *            Servicios
	 * @param pagination
	 *            Pagination
	 * @param startsWith
	 *            Boolean
	 * @return List
	 */
	@Transactional(readOnly = true)
	public List<Servicios> findAllLike(Servicios servicios,
			Pagination pagination, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.IDSERVICIO IDSERVICIO,t1.CSERVICIO CSERVICIO,t1.ESERVICIO ESERVICIO,t1.BAJA BAJA ");
		query.append("FROM SERVICIOS t1 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(servicios, 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);
		} else {
			if (LocaleContextHolder.getLocale().getLanguage()
					.equals(Aa20bConstantes.IDIOMA_EUSKERA))
				query.append(" ORDER BY t1.BAJA, t1.ESERVICIO");
			else
				query.append(" ORDER BY t1.BAJA, t1.CSERVICIO");
		}

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

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

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(servicios, 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 Servicios entity
	 * 
	 * @param servicios
	 *            Servicios 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(Servicios servicios) {

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

		if (servicios != null && servicios.getIdservicio() != null
				&& servicios.getIdservicio() != 0) {
			where.append(" AND t1.IDSERVICIO = ?");
			params.add(servicios.getIdservicio());
		}
		if (servicios != null && servicios.getCservicio() != null) {
			where.append(" AND t1.CSERVICIO = ?");
			params.add(servicios.getCservicio());
		}
		if (servicios != null && servicios.getEservicio() != null) {
			where.append(" AND t1.ESERVICIO = ?");
			params.add(servicios.getEservicio());
		}
		if (servicios != null && servicios.getBaja() != null) {
			where.append(" AND t1.BAJA = ?");
			params.add(servicios.getBaja());
		}

		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 Servicios entity
	 * 
	 * @param servicios
	 *            Servicios 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(Servicios servicios,
			Boolean startsWith) {

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

		if (servicios != null && servicios.getIdservicio() != null
				&& servicios.getIdservicio() != 0) {
			where.append(" AND t1.IDSERVICIO = ?");
			params.add(servicios.getIdservicio());
		}
		if (servicios != null && servicios.getCservicio() != null) {
			where.append(" AND UPPER(t1.CSERVICIO) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(servicios.getCservicio().toUpperCase() + "%");
			} else {
				params.add("%" + servicios.getCservicio().toUpperCase() + "%");
			}
			where.append(" AND t1.CSERVICIO IS NOT NULL");
		}
		if (servicios != null && servicios.getEservicio() != null) {
			where.append(" AND UPPER(t1.ESERVICIO) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(servicios.getEservicio().toUpperCase() + "%");
			} else {
				params.add("%" + servicios.getEservicio().toUpperCase() + "%");
			}
			where.append(" AND t1.ESERVICIO IS NOT NULL");
		}
		if (servicios != null && servicios.getBaja() != null) {
			where.append(" AND UPPER(t1.BAJA) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(servicios.getBaja().toUpperCase() + "%");
			} else {
				params.add("%" + servicios.getBaja().toUpperCase() + "%");
			}
			where.append(" AND t1.BAJA 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;
}
