package com.fp.person.rules.save;

import java.util.List;

import com.fp.dto.helper.FileHelper;
import com.fp.dto.rules.TransactionRule;
import com.fp.dto.save.SaveRequest;
import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pcustomer.people.TcustPeople;
import com.fp.persistence.pcustomer.people.TcustPeopleKey;
import com.fp.persistence.pgeneral.image.TgeneFiles;
import com.fp.persistence.pgeneral.image.TgeneFilesDetail;
import com.fp.persistence.pgeneral.image.TgeneFilesDetailKey;
import com.fp.sessionbeans.helper.Sequence;

/**
 * Clase que se encarga de subir a la BDD la imagen y asociar la foto y firma
 * del cliente
 * 
 * @author scastillo
 */
public class PersonImage extends TransactionRule {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Metodo que agrega una imagen en la base de datos
	 * 
	 * @param pSaveRequest
	 * @return
	 * @throws Exception
	 */
	@Override
	public SaveRequest normalProcess(SaveRequest pSaveRequest) throws Exception {
		Integer personcode = (Integer) pSaveRequest.get("pk_personcode");
		Integer photocode = (Integer) pSaveRequest.get("photocode");
		Integer signaturecode = (Integer) pSaveRequest.get("signaturecode");
		List<FileHelper> fileItem = (List<FileHelper>) pSaveRequest.get("file");
		if (fileItem.isEmpty() || fileItem.size() != 2) {
			return pSaveRequest;
		}
		TcustPeople tcustPeople=null;
		//TcustPeopleKey tcustPeopleKey = new TcustPeopleKey(personcode,FormatDates.getDefaultExpiryTimestamp());
		tcustPeople = (TcustPeople) pSaveRequest.getSaveBeanModifiedObject("TCUSTPEOPLE");
		if(tcustPeople==null){
			TcustPeopleKey tcustPeopleKey = new TcustPeopleKey(personcode,FormatDates.getDefaultExpiryTimestamp());
			tcustPeople = TcustPeople.find(PersistenceHelper.getEntityManager(), tcustPeopleKey);
		}
		photocode = this.buildImageCode(photocode, fileItem.get(0),pSaveRequest);
		signaturecode = this.buildImageCode(signaturecode, fileItem.get(1),	pSaveRequest);
		if (tcustPeople!=null && tcustPeople.getPhotocode() == null && photocode != null) {
			tcustPeople.setPhotocode(photocode);
			tcustPeople.setModifyusercode(pSaveRequest.getUser());
		}
		if (tcustPeople!=null && tcustPeople.getSignaturecode() == null && signaturecode != null) {
			tcustPeople.setSignaturecode(signaturecode);
			tcustPeople.setModifyusercode(pSaveRequest.getUser());
		}
		
		pSaveRequest.getResponse().put("codes",	"["+ photocode + "," + signaturecode + "]");
		return pSaveRequest;
	}

	/**
	 * Metodo que se ejecuta en modo reverso
	 * 
	 * @param pSaveRequest
	 * @return
	 * @throws Exception
	 */
	@Override
	public SaveRequest reverseProcess(SaveRequest pSaveRequest)
			throws Exception {
		return pSaveRequest;
	}

	/**
	 * Metodo que devuelve la secuencia que le pertenece a una nueva imagen.
	 * 
	 * @return Codigo de la nueva persona.
	 * @throws Exception
	 */
	public static Integer getFileCode() throws Exception {
		Sequence sequence = new Sequence();
		return Integer.valueOf(sequence.getNextValue("FILECODE").toString());
	}

	/**
	 * Metodo que se encarga de construir la imagen
	 * 
	 * @param photocode
	 * @param fileItem
	 * @param saveRequest
	 * @throws Exception
	 */
	private Integer buildImageCode(Integer photocode, FileHelper fileItem,
			SaveRequest saveRequest) throws Exception {
		if (!fileItem.getName().equals("")) {
			if (fileItem.getExtension().toLowerCase().compareTo("jpg") == 0					
					|| fileItem.getExtension().toLowerCase().compareTo("gif") == 0					
					|| fileItem.getExtension().toLowerCase().compareTo("jpeg") == 0					
					|| fileItem.getExtension().toLowerCase().compareTo("png") == 0) {
				if (photocode == null) {
					photocode = getFileCode();
					TgeneFiles tgeneFiles = new TgeneFiles(photocode);
					PersistenceHelper.save(tgeneFiles);
				}
				TgeneFilesDetailKey tgeneFilesDetailKey = new TgeneFilesDetailKey(photocode, FormatDates.getDefaultExpiryTimestamp());
				TgeneFilesDetail tgeneFilesDetail = TgeneFilesDetail.find(PersistenceHelper.getEntityManager(),tgeneFilesDetailKey);
				if (tgeneFilesDetail == null) {
					tgeneFilesDetail = new TgeneFilesDetail(tgeneFilesDetailKey);
					tgeneFilesDetail.setImage(fileItem.getImage());
					tgeneFilesDetail.setCapturedate(FormatDates.getInstance().getDataBaseDate());
					tgeneFilesDetail.setImagesize(Integer.parseInt(String.valueOf(fileItem.getSize())));
					tgeneFilesDetail.setIngressuser(saveRequest.getUser());
					tgeneFilesDetail.setExtension(fileItem.getExtension());
					PersistenceHelper.save(tgeneFilesDetail);
				} else {
					tgeneFilesDetail.setImage(fileItem.getImage());
					tgeneFilesDetail.setCapturedate(FormatDates.getInstance().getDataBaseDate());
					tgeneFilesDetail.setImagesize(Integer.parseInt(String.valueOf(fileItem.getSize())));
					tgeneFilesDetail.setModifyuser(saveRequest.getUser());
					tgeneFilesDetail.setExtension(fileItem.getExtension());
					PersistenceHelper.saveOrUpdate(tgeneFilesDetail);
				}
			} else {
				throw new GeneralException("CUST-0007",
						"LOS TIPOS DE ARCHIVOS PERMITIDOS SON  JPG, JPEG, GIF Y PNG");
			}
		}
		return photocode;
	}
}