package com.fp.person.rules.save;

import java.util.List;

import com.fp.common.helper.Constant;
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.pcustomer.gene.TcustPersonAddress;
import com.fp.persistence.pcustomer.gene.TcustPersonPhone;

public class ValidateAddressPhones extends TransactionRule {

    @Override
    public SaveRequest normalProcess(SaveRequest pSaveRequest) throws Exception {
        Integer personcode = null;
        Object objpersoncode = pSaveRequest.get("personcode");
        if (objpersoncode instanceof String) {
            personcode = Integer.parseInt(objpersoncode.toString());
        } else if (objpersoncode instanceof String) {
            personcode = (Integer) objpersoncode;
        }

        if ((pSaveRequest.get("TCUSTPERSONADDRESS") == null) && (pSaveRequest.get("TCUSTPERSONPHONE") == null)) {
            return pSaveRequest;
        }

        List<Object> laddressdel = pSaveRequest.getSaveBeanDeletedRecords("TCUSTPERSONADDRESS");
        List<Object> laddressmod = pSaveRequest.getSaveBeanModifiedRecords("TCUSTPERSONADDRESS");
        List<TcustPersonAddress> laddressbase = TcustPersonAddress.findByPersonCode(PersistenceHelper.getEntityManager(), personcode);

        List<TcustPersonAddress> laddressFinal = Constant.getFinalList(laddressbase, Constant.convertList(laddressmod, TcustPersonAddress.class),
                Constant.convertList(laddressdel, TcustPersonAddress.class));

        if ((laddressFinal == null) || laddressFinal.isEmpty()) {
            throw new GeneralException("CUST-0011", "SE NECESITA INGRESAR UNA DIRECCIÓN");
        }

        List<Object> lphonesdel = pSaveRequest.getSaveBeanDeletedRecords("TCUSTPERSONPHONE");
        List<Object> lphonesmod = pSaveRequest.getSaveBeanModifiedRecords("TCUSTPERSONPHONE");
        List<TcustPersonPhone> lphonebase = TcustPersonPhone.findPhones(PersistenceHelper.getEntityManager(), personcode,
                Constant.getDefaultExpiryTimestamp());

        List<TcustPersonPhone> lphoneFinal = Constant.getFinalList(lphonebase, Constant.convertList(lphonesmod, TcustPersonPhone.class),
                Constant.convertList(lphonesdel, TcustPersonPhone.class));

        if ((lphoneFinal == null) || lphoneFinal.isEmpty()) {
            throw new GeneralException("CUST-0012", "NECESITA UN REGISTRO TELEFÓNICO");
        }

        return pSaveRequest;
    }

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

}
