package com.fp.armas.rules.query.webservices;

import java.util.List;

import javax.persistence.Query;

import com.fp.armas.rules.query.webservices.util.PersonaUtil;
import com.fp.common.logger.APPLogger;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;

/**
 * Servicio que retorna un 0 si existe el login, 1 si es incorrecto
 * @author dcruz
 *
 */
public class ConsultaLogin extends QueryRule {

	private static final long serialVersionUID = -1758582166779180497L;
	private static final String QUERY_USER = "SELECT o FROM TsafeUserDetail o WHERE o.pk.usercode=:usercode AND o.pk.dateto=:dateto";

	@SuppressWarnings("unchecked")
	@Override
	public QueryRequest process(QueryRequest pRequest) throws Exception {
		try {
			String usercode = (String) pRequest.get("USERCODE");
			String password = (String) pRequest.get("PASSWORD");
			if(password != null){//Servicio consulta login password
				StringBuilder sb = new StringBuilder(QUERY_USER);
				sb.append(" AND o.password=:password");
				Query query = PersistenceHelper.getEntityManager().createQuery(sb.toString());
				query.setParameter("usercode", usercode);
				query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
				query.setParameter("password", password);
				List<TsafeUserDetail> ltsafeUserDetails = query.getResultList();
				if(ltsafeUserDetails != null && !ltsafeUserDetails.isEmpty()){
					TsafeUserDetail tsafeUserDetail = ltsafeUserDetails.iterator().next();
					String localidad = PersonaUtil.getInstancia().obtenerLocacionPersona(tsafeUserDetail.getPk().getPersoncode());
					pRequest.getResponse().put("RESPUESTA", localidad.toString());
				}
			} else {//Servicio consulta login
				Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_USER);
				query.setParameter("usercode", usercode);
				query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
				List<TsafeUserDetail> ltsafeUserDetails = query.getResultList();
				if(ltsafeUserDetails != null && !ltsafeUserDetails.isEmpty()){
					pRequest.getResponse().put("RESPUESTA", "0");
				}else{
					pRequest.getResponse().put("RESPUESTA", "1");
				}
			}
		} catch (Throwable e) {
			APPLogger.getLogger().error(e.getMessage(), e);
			pRequest.getResponse().put("RESPUESTA", "2");
		}
		return pRequest;
	}

}
