package com.fp.person.rules.save;

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.company.TcustCompany;
import com.fp.persistence.pcustomer.company.TcustCompanyKey;
import com.fp.persistence.pgeneral.image.TgeneFiles;
import com.fp.persistence.pgeneral.image.TgeneFilesDetail;
import com.fp.persistence.pgeneral.image.TgeneFilesDetailKey;
import java.sql.Timestamp;
import java.util.List;

/**
 * Clase que se encarga de agregar o modificar los logos de una empresa
 *
 * @author scastillo
 */
public class LogoImage extends TransactionRule {

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

    /**
     * Metodo que genera el numero de sequencia de imagenes para el logo de
     * empresas
     *
     * @param sr
     * @return
     * @throws Exception
     */
    @Override
    public SaveRequest normalProcess(SaveRequest sr) throws Exception {
        Integer personcode = (Integer) sr.get("pk_personcode");
        Integer logocode = (Integer) sr.get("logocode");
        List<FileHelper> fileItem = (List<FileHelper>) sr.get("file");
        if (fileItem!=null && !fileItem.isEmpty() && fileItem.size() == 1) {
        	if(fileItem.get(0).getExtension() != null){
        		if (fileItem.get(0).getExtension().toLowerCase().compareTo("jpg") == 0
                        || fileItem.get(0).getExtension().toLowerCase().compareTo("gif") == 0
                        || fileItem.get(0).getExtension().toLowerCase().compareTo("png") == 0
                        || fileItem.get(0).getExtension().toLowerCase().compareTo("jpeg") == 0
                                ) {
                    int contador = 1;
                    if (logocode == null) {
                        logocode = PersonImage.getFileCode();
                        TgeneFiles tgeneFiles = new TgeneFiles();
                        tgeneFiles.setPk(logocode);
                        sr.putSaveBean("TGENEFILES", tgeneFiles, (contador++));
                    }
                    TgeneFilesDetailKey tgeneFilesDetailKey = new TgeneFilesDetailKey();
                    tgeneFilesDetailKey.setCode(logocode);
                    Timestamp fechaactual = FormatDates.getInstance().getDataBaseTimestamp();
                    TgeneFilesDetail tgeneFilesDetail = TgeneFilesDetail.find(
                            PersistenceHelper.getEntityManager(),
                            tgeneFilesDetailKey);
                    if (tgeneFilesDetail == null) {
                        tgeneFilesDetail = new TgeneFilesDetail();
                        tgeneFilesDetail.setPk(tgeneFilesDetailKey);
                        tgeneFilesDetail.setImage(fileItem.get(0).getImage());
                        tgeneFilesDetail.setCapturedate(FormatDates.getInstance().getDataBaseDate());
                        tgeneFilesDetail.setImagesize(Integer.parseInt(String.valueOf(fileItem.get(0).getSize())));
                        tgeneFilesDetail.setIngressuser(sr.getUser());
                        tgeneFilesDetail.setExtension(fileItem.get(0).getExtension());
                        tgeneFilesDetail.setContenttype(fileItem.get(0).getContentType());
                        tgeneFilesDetail.setName(fileItem.get(0).getName());
                    } else {
                        tgeneFilesDetail.setImage(fileItem.get(0).getImage());
                        tgeneFilesDetail.setCapturedate(FormatDates.getInstance().getDataBaseDate());
                        tgeneFilesDetail.setImagesize(Integer.parseInt(String.valueOf(fileItem.get(0).getSize())));
                        tgeneFilesDetail.setDatefrom(fechaactual);
                        tgeneFilesDetail.setModifyuser(sr.getUser());
                        tgeneFilesDetail.setContenttype(fileItem.get(0).getContentType());
                        tgeneFilesDetail.setName(fileItem.get(0).getName());
                        PersistenceHelper.getEntityManager().detach(
                                tgeneFilesDetail);
                    }
                    sr.putSaveBean("TGENEFILESDETAIL", tgeneFilesDetail,
                            (contador++));
                    TcustCompanyKey tcustCompanyKey = new TcustCompanyKey();
                    tcustCompanyKey.setPersoncode(personcode);
                    tcustCompanyKey.setDateto(FormatDates.getDefaultExpiryTimestamp());
                    TcustCompany tcustCompany = TcustCompany.find(
                            PersistenceHelper.getEntityManager(), tcustCompanyKey);
                    tcustCompany.setModifyuser(sr.getUser());
                    tcustCompany.setPicture(fileItem.get(0).getImage());
                    tcustCompany.setLogo(logocode);
                    tcustCompany.setDatefrom(fechaactual);
                    PersistenceHelper.getEntityManager().detach(tcustCompany);
                    sr.putSaveBean("TCUSTCOMPANY", tcustCompany, (contador++));
                } else {
                    throw new GeneralException("CUST-0007", "Los tipos de archivos permitidos son  jpg, jpeg, gif y png");
                }
        	}
        }
        sr.getResponse().put("codes", "[" + logocode + "]");
        return sr;
    }

    @Override
    public SaveRequest reverseProcess(SaveRequest sr) throws Exception {
        return sr;
    }
}
