package com.fp.armas.rules.save.armas;

import java.sql.Date;
import java.util.List;

import javax.persistence.Query;

import com.fp.armas.rules.exception.ControlArmasException;
import com.fp.common.helper.Constant;
import com.fp.dto.rules.TransactionRule;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.parmas.fun.TarmRegistroArmas;
import com.fp.persistence.parmas.soli.TarmArmas;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.sessionbeans.helper.Sequence;

/**
 * Registra las armas y el registro de armas
 * @author dcruz
 *
 */
public class ArmasRegistro extends TransactionRule {

	private static final long serialVersionUID = 1L;
	private static final String QUERY_PERSONA_ID = "SELECT o FROM TcustPersonDetail o WHERE o.identification=:identification AND o.pk.dateto=:dateto";

	@SuppressWarnings("unchecked")
	@Override
	public SaveRequest normalProcess(SaveRequest pSaveRequest) throws Exception {
		if(pSaveRequest.get("eseliminacion") == null || !Constant.ifYes(pSaveRequest.get("eseliminacion").toString())){
			TarmRegistroArmas registro = (TarmRegistroArmas) pSaveRequest.getSaveBeanModifiedObject("TREGISTROARMAS");
			if(registro != null){
				if(registro.isIsnew()){
					Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_PERSONA_ID);
					query.setParameter("identification", pSaveRequest.get("NUMDOC").toString());
					query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
					List<TcustPersonDetail> ltcustPersonDetail = query.getResultList();
					if(ltcustPersonDetail != null && !ltcustPersonDetail.isEmpty()){
						TcustPersonDetail tcustPersonDetail = ltcustPersonDetail.iterator().next();
						registro.setPersoncode(tcustPersonDetail.getPk().getPersoncode());
					} else{
						throw new ControlArmasException("ARM-001", "La datos de la persona ingresada no existen, por favor crear primero la persona ");
					}
					registro.setPk(getCodigoRegistro());
					registro.setTiporegistrocodigo("TIPOREGISTRO");
					registro.setFcreacion(new Date(System.currentTimeMillis()));
				}
				List<Object> armasList = pSaveRequest.getSaveBeanModifiedRecords("ARMAS");
				for (Object object : armasList) {
					TarmArmas arma = (TarmArmas) object;
					arma.setCregistro(registro.getPk());
					if(arma.getColor() != null){
						arma.setColorcodigo("COLOR");
					}
					if(arma.getTipofabricacion() != null){
						arma.setTipofabricacioncodigo("TIPOFABRICACION");
					}
					if(arma.getUnidadmedidacantidad() != null){
						arma.setUnidadmedidacantidadcodigo("UNIDADMEDIDA");
					}
					
					if(arma.isIsnew()){
						arma.setPk(this.getCodigoArma());
						arma.setFecharegistro(new Date(System.currentTimeMillis()));
						arma.setCodigoarma(arma.getPk());
					} 
					//arma.setIsnew(Boolean.TRUE);
				}
			}else{
				List<Object> armasList = pSaveRequest.getSaveBeanModifiedRecords("ARMAS");
				for (Object object : armasList) {
					TarmArmas arma = (TarmArmas) object;
					if(arma.getColor() != null){
						arma.setColorcodigo("COLOR");
					}
					if(arma.getTipofabricacion() != null){
						arma.setTipofabricacioncodigo("TIPOFABRICACION");
					}
					if(arma.getUnidadmedidacantidad() != null){
						arma.setUnidadmedidacantidadcodigo("UNIDADMEDIDA");
					}
					if(arma.isIsnew()){
						arma.setIsnew(Boolean.TRUE);
						arma.setPk(this.getCodigoArma());
						arma.setFecharegistro(new Date(System.currentTimeMillis()));
						arma.setCodigoarma(arma.getPk());
					}
				}
			}
		}
		return pSaveRequest;
	}

	@Override
	public SaveRequest reverseProcess(SaveRequest pSaveRequest) throws Exception {
		return pSaveRequest;
	}
	
	private Long getCodigoRegistro() throws Exception{
		Sequence sequence = new Sequence();
		Long cregistro = sequence.getNextValue("CREGISTRO").longValue();
		return cregistro;
	}
	
	private String getCodigoArma() throws Exception{
		Sequence sequence = new Sequence();
		String carma = sequence.getNextValue("CARMA").toString();
		return carma;
	}

}
