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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.fp.bpm.query.QueryJsf;
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.parmas.param.TarmCentroControl;
import com.fp.persistence.pcustomer.gene.TcustPersonAddress;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pcustomer.gene.TcustPersonPhone;
import com.fp.persistence.pgeneral.gene.TgeneParameters;
import com.fp.persistence.pgeneral.gene.TgeneParametersKey;

@SuppressWarnings("serial")
public class CompletaDatosInspeccionPlan extends QueryRule{

	private EntityManager em = null;
	private String jpqlPersona = "select p.pk.personcode, "
			+ "(select c.description from TgeneCatalogDetail c where c.pk.catalog = p.identificationcatalog and c.pk.catalogcode = p.identificationcatalogcode) as tipodoc, "
			+ " p.identification,"
			+ " p.name,"
			+ " p.legalrepresentidentification,"
			+ " p.legalrepresent"
			+ " from TcustPersonDetail p "
			+ " where p.pk.personcode = :personcode and p.pk.dateto = :dateto";
	private String jpqlPersonaDireccion = "select p.addresstypecatalog, "
			+ " p.address, "
			+ " p.remark, "
			+ " (select o.description from TgeneProvince  o where o.pk.countrycode='EC'   and  o.pk.provincecode=p.provincecode)  as provincia,"
			+ " (select o.description from TgeneCanton    o where o.pk.countrycode='EC'   and  o.pk.provincecode=p.provincecode and o.pk.cantoncode=p.cantoncode) as canton,"
			+ " (select o.description from TgeneCity      o where o.pk.countrycode='EC'   and  o.pk.provincecode=p.provincecode and o.pk.cantoncode=p.cantoncode and o.pk.citycode=p.citycode) as ciudad,"
			+ " (select o.description from TgeneParroquia o where o.pk.countrycode='EC'   and  o.pk.provincecode=p.provincecode and o.pk.cantoncode=p.cantoncode and o.pk.parroquiacode=p.parroquiacode) as parroquia"
			+ " from TcustPersonAddress p "
			+ " where p.pk.personcode = :personcode and p.pk.dateto = :dateto";
	
	Map<String, Object> persona = new HashMap<String, Object>();
	private String codigoPhoneFijo;
	private String codigoPhoneCelular;
	private String codigoMail;
	private String codigoOficina;
	@Override
	public QueryRequest process(QueryRequest pQueyRequest) throws Exception {
		QueryJsf query = new QueryJsf();
		query.execute(pQueyRequest);
		em = PersistenceHelper.getEntityManager();
		TcustPersonDetail personDetailResp = (TcustPersonDetail)pQueyRequest.getResponse().get("REGINSPECPLANINO");
		completarResponsable(personDetailResp);
		Integer personCodePropietario=Integer.parseInt(pQueyRequest.get("personcodepropietario").toString());
		String ccentrocontrol =pQueyRequest.get("ccentrocontrol").toString();	
		//propietario  1
		dataPerson(personCodePropietario);
		direccion(personCodePropietario);
		telefonoPropietario(personCodePropietario);
		pQueyRequest.getResponse().put("PERSONAPROPIETARIO", persona);
		return pQueyRequest;
	}

	private void dataPerson(Integer personcode) throws Exception{
		Query qry = this.em.createQuery(this.jpqlPersona);
		qry.setParameter("personcode", personcode);
		qry.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
		Object[] objeto = (Object[])qry.getSingleResult();
		if(objeto!=null){
			persona.put("personcode", objeto[0]);
			persona.put("tipoidentificacion", objeto[1]);
			persona.put("identification", objeto[2]);
			persona.put("name", objeto[3]);
			persona.put("legalrepresentidentification", objeto[4]);
			persona.put("legalrepresent", objeto[5]);
		}
	}
	@SuppressWarnings("unchecked")
	public void direccion(Integer personcode) throws Exception{
		codigoMail=codigoParameter("CODIGO.MAIL");
		Query qry2 = this.em.createQuery(this.jpqlPersonaDireccion);
		qry2.setParameter("personcode", personcode);
		qry2.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
		List<Object> ldirecciones = qry2.getResultList();
		
		for(Object direc:ldirecciones){
			Object[] objeto=(Object[])direc;
			//correo
			if(objeto[0]!=null && objeto[0].equals(codigoMail)){
				if(objeto[1]!=null){
					persona.put("mail", objeto[1]);
				}
			}else{
				if(objeto[1]!=null){
					persona.put("address", objeto[1]);
				}
				
				if(objeto[2]!=null){
					persona.put("remark", objeto[2]);
				}
				if(objeto[3]!=null){
					persona.put("provincia", objeto[3]);
				}
				if(objeto[4]!=null){
					persona.put("canton", objeto[4]);
				}
				if(objeto[5]!=null){
					persona.put("ciudad", objeto[5]);
				}
				if(objeto[6]!=null){
					persona.put("parroquia", objeto[6]);
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	private void telefonoPropietario(Integer personcode) throws Exception{
		List<TcustPersonPhone> phones =em.createQuery("select o from TcustPersonPhone o"
                + " where o.pk.personcode=:personcode and o.pk.dateto=:dateto order by o.phonetypecatalog asc")
                .setParameter("personcode", personcode)
                .setParameter("dateto", FormatDates.getDefaultExpiryTimestamp())
                .getResultList();
		for(TcustPersonPhone tel:phones){
				persona.put("telefono", tel.getPhonenumber());
				break;
		}
	}
	
	
	@SuppressWarnings("unchecked")
	private void completarResponsable(TcustPersonDetail tcustPersonDetail) throws Exception{
		codigoPhoneFijo=codigoParameter("CODIGO.PHONE.FIJO");
		codigoPhoneCelular=codigoParameter("CODIGO.PHONE.CELULAR");
		List<TcustPersonPhone> phones =em.createQuery("select o from TcustPersonPhone o"
                                                    + " where o.pk.personcode=:personcode and o.pk.dateto=:dateto")
                .setParameter("personcode", tcustPersonDetail.getPk().getPersoncode())
                .setParameter("dateto", FormatDates.getDefaultExpiryTimestamp())
                .getResultList();
		for(TcustPersonPhone telefono:phones){
			if(telefono.getPhonetypecatalog().equals(codigoPhoneFijo)){    //  CODIGO.PHONE.FIJO 
				tcustPersonDetail.getModifiedData().put("fijo", telefono.getPhonenumber());
			}else if(telefono.getPhonetypecatalog().equals(codigoPhoneCelular)){// CODIGO.PHONE.CELULAR
				tcustPersonDetail.getModifiedData().put("celular", telefono.getPhonenumber());
			}
		}
		
		//mail
		List<TcustPersonAddress> maill =em.createQuery("select o from TcustPersonAddress o"
												 + " where o.pk.personcode=:personcode and o.pk.dateto=:dateto and o.addresstypecatalog=:addresstypecatalog")
					                 .setParameter("personcode", tcustPersonDetail.getPk().getPersoncode())
					                 .setParameter("dateto", FormatDates.getDefaultExpiryTimestamp())
					                 .setParameter("addresstypecatalog", codigoMail)
					                 .getResultList();
		for(TcustPersonAddress mail:maill){
				if(mail.getAddress()!=null){
					tcustPersonDetail.getModifiedData().put("mail", mail.getAddress());
					break;
			}
		}
		
	}

	private void centroControl(String ccentrocontrol, QueryRequest sr, String tipo) throws Exception{
		TarmCentroControl centroControl= TarmCentroControl.find(this.em,ccentrocontrol);
		sr.getResponse().put("CENTROCONTROL", centroControl);
	}
	
	private String codigoParameter(String codigo) throws Exception{
		TgeneParameters parameter= TgeneParameters.find(this.em, new TgeneParametersKey(codigo, 1));
		return parameter.getTextvalue();
	}
}
