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

import java.util.List;

import javax.persistence.Query;

import com.fp.common.helper.Constant;
import com.fp.common.logger.APPLogger;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.exception.CommondbException;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.parmas.dto.ws.ImagenDto;
import com.fp.persistence.parmas.dto.ws.PersonaDto;
import com.fp.persistence.pcustomer.company.TcustCompany;
import com.fp.persistence.pcustomer.company.TcustCompanyKey;
import com.fp.persistence.pcustomer.gene.TcustPersonAddress;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pcustomer.people.TcustPeople;
import com.fp.persistence.pcustomer.people.TcustPeopleKey;
import com.fp.persistence.pgeneral.image.TgeneFilesDetail;
import com.fp.persistence.pgeneral.image.TgeneFilesDetailKey;

/**
 * Clase utilitaria que colocar&aacute; los datos de la persona
 * @author dcruz
 *
 */
public class PersonaUtil {
	/**
	 * Consulta propia de la persona
	 */
	private static final String QUERY_PERSONA = "SELECT o FROM TcustPersonDetail o WHERE o.pk.personcode=:personcode AND o.pk.dateto=:dateto";
	private static final String QUERY_DIRECCION_PRINCIPAL="SELECT o FROM TcustPersonAddress o WHERE o.pk.personcode=:personcode AND o.pk.dateto=:dateto AND o.principal=:principal";
	private static final String QUERY_PROVINCIA = "SELECT o.description FROM TgeneProvince o WHERE o.pk.countrycode=:countrycode AND o.pk.provincecode=:provincecode";
	private static final String QUERY_CANTON = "SELECT o.description FROM TgeneCanton o WHERE o.pk.countrycode=:countrycode AND o.pk.provincecode=:provincecode AND o.pk.cantoncode=:cantoncode";
	private static final String QUERY_PARROQUIA = "SELECT o.description FROM TgeneParroquia o WHERE o.pk.countrycode=:countrycode AND o.pk.provincecode=:provincecode AND o.pk.cantoncode=:cantoncode AND o.pk.parroquiacode=:parroquiacode";
	private static final String QUERY_TELEFONO = "SELECT o.phonenumber FROM TcustPersonPhone o WHERE o.pk.personcode=:personcode AND o.addressnumber=:addressnumber";
	private static PersonaUtil INSTANCIA = new PersonaUtil();
	
	private PersonaUtil(){}
	
	public static PersonaUtil getInstancia() {
		return INSTANCIA;
	}
	
	/**
	 * Obtiene todos los datos de la persona a enviar en a trav&eacute;s del web service
	 * @param personCode
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public PersonaDto obtenerPersonaPorId(Integer personcode, String usercode) throws Exception{
		PersonaDto persona = null;
		if(personcode == null){
			return persona;
		}
		TcustPersonDetail tcustPersonDetail = null;
		Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_PERSONA);
		query.setParameter("personcode", personcode);
		query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
		List<TcustPersonDetail> lpersonDetail = query.getResultList();
		if(lpersonDetail != null && !lpersonDetail.isEmpty()){
			persona = new PersonaDto();
			tcustPersonDetail = lpersonDetail.get(0);
			persona.setCodigoPersona(tcustPersonDetail.getPk().getPersoncode());
			persona.setCodigoUsuario(usercode);
			persona.setTipoIdentificacion(tcustPersonDetail.getIdentificationcatalog());
			persona.setIdentificacion(tcustPersonDetail.getIdentification());
			persona.setNombre(tcustPersonDetail.getName());
			persona.setRepresentanteLegal(tcustPersonDetail.getLegalrepresent());
			//Obtenemos la direccion principal de la persona
			TcustPersonAddress tcustPersonAddress = obtieneDireccionPrincipal(personcode);
			persona.setDireccion(tcustPersonAddress.getAddress());
			persona.setProvincia(obtenerProvincia(tcustPersonAddress.getProvincecode()));
			persona.setCanton(obtenerCanton(tcustPersonAddress.getProvincecode(), tcustPersonAddress.getCantoncode()));
			persona.setParroquia(obtenerParroquia(tcustPersonAddress.getProvincecode(), tcustPersonAddress.getCantoncode(), tcustPersonAddress.getParroquiacode()));
			persona.setTelefono(obtenerNumeroTelefono(tcustPersonAddress.getPk().getPersoncode(), tcustPersonAddress.getPk().getAddressnumber()));
			if(tcustPersonDetail.getMilitarygrade() != null && tcustPersonDetail.getMilitarygradecode() != null){
				persona.setGrado(CatalogoUtil.getInstancia().getLegalCode(tcustPersonDetail.getMilitarygrade(), tcustPersonDetail.getMilitarygradecode()));
			}
		}
		return persona;
	}
	
	/**
	 * Obtiene la direcci&oacute;n principal de la persona
	 * @param personcode
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public TcustPersonAddress obtieneDireccionPrincipal(Integer personcode) throws Exception {
		TcustPersonAddress tcustPersonAddress = null;
		Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_DIRECCION_PRINCIPAL);
		query.setParameter("personcode", personcode);
		query.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
		query.setParameter("principal", Constant.STR_Y);
		List<TcustPersonAddress> ltcustPersonAddresses = query.getResultList();
		if(ltcustPersonAddresses != null && !ltcustPersonAddresses.isEmpty()){
			tcustPersonAddress = ltcustPersonAddresses.iterator().next();
		}
		return tcustPersonAddress;
	}
	
	/**
	 * Obtiene la descripci&oacute;n de la provincia
	 * @param provincecode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String obtenerProvincia(String provincecode) {
		String provincia = null;
		Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_PROVINCIA);
		query.setParameter("countrycode", "EC");
		query.setParameter("provincecode", provincecode);
		List<String> lprovincias = query.getResultList();
		if(lprovincias != null && !lprovincias.isEmpty()){
			provincia = lprovincias.iterator().next();
		}
		return provincia;
	}
	
	/**
	 * Obtiene la descripci&oacute;n del cant&oacute;n
	 * @param provincecode
	 * @param cantoncode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String obtenerCanton(String provincecode, String cantoncode) {
		String canton = null;
		Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_CANTON);
		query.setParameter("countrycode", "EC");
		query.setParameter("provincecode", provincecode);
		query.setParameter("cantoncode", cantoncode);
		List<String> lcanton = query.getResultList();
		if(lcanton != null && !lcanton.isEmpty()){
			canton = lcanton.iterator().next();
		}
		return canton;
	}
	
	/**
	 * Obtiene la descrici&oacute;n de la parroquia
	 * @param provincecode
	 * @param cantoncode
	 * @param parroquiacode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String obtenerParroquia(String provincecode, String cantoncode, String parroquiacode) {
		String parroquia = null;
		Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_PARROQUIA);
		query.setParameter("countrycode", "EC");
		query.setParameter("provincecode", provincecode);
		query.setParameter("cantoncode", cantoncode);
		query.setParameter("parroquiacode", parroquiacode);
		List<String> lparroquia = query.getResultList();
		if(lparroquia != null && !lparroquia.isEmpty()){
			parroquia = lparroquia.iterator().next();
		}
		return parroquia;
	}
	
	/**
	 * Obtiene el tel&eacute;fono segun la direcci&oacute;n asociada
	 * @param personcode
	 * @param addressnumber
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String obtenerNumeroTelefono(Integer personcode, Integer addressnumber) {
		String telefono = null;
		Query query = PersistenceHelper.getEntityManager().createQuery(QUERY_TELEFONO);
		query.setParameter("personcode", personcode);
		query.setParameter("addressnumber", addressnumber);
		List<String> ltelefono = query.getResultList();
		if(ltelefono != null && !ltelefono.isEmpty()){
			telefono = ltelefono.iterator().next();
		}
		return telefono;
	}
	
	/**
	 * Retorna la localizaci&oacute;n de donde se encuentra la persona
	 * @param personcode
	 * @return
	 */
	public String obtenerLocacionPersona(Integer personcode) {
		StringBuffer sb = new StringBuffer();
		try {
			TcustPersonAddress tcustPersonAddress = obtieneDireccionPrincipal(personcode);
			sb.append(tcustPersonAddress.getProvincecode()).append(",").append(obtenerProvincia(tcustPersonAddress.getProvincecode())).append("/");
			sb.append(tcustPersonAddress.getCantoncode()).append(",").append(obtenerCanton(tcustPersonAddress.getProvincecode(), tcustPersonAddress.getCantoncode())).append("/");
			sb.append(tcustPersonAddress.getParroquiacode()).append(",").append(obtenerParroquia(tcustPersonAddress.getProvincecode(), tcustPersonAddress.getCantoncode(), tcustPersonAddress.getParroquiacode()));
		} catch (CommondbException e) {
		} catch (Exception e) {
		}
		return sb.toString();
	}
	
	/**
	 * Retorna la foto o el logo de la persona si es que esta existe
	 * @param personcode
	 * @return
	 */
	public ImagenDto obtenerImagen(Integer personcode) {
		System.out.println("ImagenDto obtenerImagen......-----------"+personcode);
		ImagenDto imagenDto = null;
		TgeneFilesDetail tgeneFilesDetail = null;
		try {
			TcustCompany tcustCompany = TcustCompany.find(PersistenceHelper.getEntityManager(), new TcustCompanyKey(personcode, FormatDates.getDefaultExpiryTimestamp()));
			if(tcustCompany != null){
				tgeneFilesDetail = TgeneFilesDetail.find(PersistenceHelper.getEntityManager(), new TgeneFilesDetailKey(tcustCompany.getLogo(), FormatDates.getDefaultExpiryTimestamp()));
        	 } else{
				TcustPeople tcustPeople = TcustPeople.find(PersistenceHelper.getEntityManager(), new TcustPeopleKey(personcode, FormatDates.getDefaultExpiryTimestamp()));
				if(tcustPeople != null){
					tgeneFilesDetail = TgeneFilesDetail.find(PersistenceHelper.getEntityManager(), new TgeneFilesDetailKey(tcustPeople.getPhotocode(), FormatDates.getDefaultExpiryTimestamp()));
				}
			}
			if(tgeneFilesDetail != null){
				imagenDto = new ImagenDto();
				imagenDto.setCodigoImagen(tgeneFilesDetail.getPk().getCode());
				imagenDto.setExtension(tgeneFilesDetail.getExtension());
				imagenDto.setImagen(tgeneFilesDetail.getImage());
				imagenDto.setTamanioImagen(tgeneFilesDetail.getImagesize());
				imagenDto.setTipoContenido(tgeneFilesDetail.getContenttype());
			}
		} catch (Throwable e) {
			APPLogger.getLogger().error(e.getMessage(), e);
		}
		return imagenDto;
	}
}
