package com.fp.general.rules.save;

import java.math.BigDecimal;
import java.util.ArrayList;
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.pgeneral.charge.TgeneSubProductCharges;

/**
 * Clase que se encarga de verificar traslape en montos de los cargos.
 * 
 * @author Angel Merchan.
 * @version 2.1
 * 
 */
@SuppressWarnings("serial")
public class VerifyOverlapSubProductChargesAmount extends TransactionRule {

    @Override
    public SaveRequest normalProcess(SaveRequest pSaveRequest) throws Exception {
        if (pSaveRequest.getSaveBean("TGENESUBPRODUCTCHARGES") != null) {
            this.validateTgeneSubProductCharges(pSaveRequest);
        }

        return pSaveRequest;
    }

    private void validateTgeneSubProductCharges(SaveRequest pSaveRequest) throws Exception {
        String modulecode = pSaveRequest.get("modulecode").toString();
        String productcode = pSaveRequest.get("productcode").toString();
        String subproductcode = pSaveRequest.get("subproductcode").toString();

        List<Object> lSubProductChargesModified = pSaveRequest.getSaveBeanModifiedRecords("TGENESUBPRODUCTCHARGES");
        List<Object> lSubProductChargesDeleted = pSaveRequest.getSaveBeanDeletedRecords("TGENESUBPRODUCTCHARGES");
        List<TgeneSubProductCharges> listSubProductChargesDatabase = TgeneSubProductCharges.find(PersistenceHelper.getEntityManager(), modulecode,
                productcode, subproductcode);
        List<TgeneSubProductCharges> listSubProductChargesFinal = new ArrayList<TgeneSubProductCharges>();

        listSubProductChargesFinal = Constant.getFinalList(listSubProductChargesDatabase,
                Constant.convertList(lSubProductChargesModified, TgeneSubProductCharges.class),
                Constant.convertList(lSubProductChargesDeleted, TgeneSubProductCharges.class));

        for (int i = 0; i < listSubProductChargesFinal.size(); i++) {
            TgeneSubProductCharges prodchargesfinal = listSubProductChargesFinal.get(i);
            this.validateOverlapSubProductCharges(prodchargesfinal, i + 1, listSubProductChargesFinal);
        }
    }

    /**
     * Metodo que verifica el traslape de montos de un cargo
     * 
     * @param prodchargesfinal
     * @param index
     * @param listSubProductChargesFinal
     * @throws Exception
     */
    private void validateOverlapSubProductCharges(TgeneSubProductCharges prodchargesfinal, int index,
            List<TgeneSubProductCharges> listSubProductChargesFinal) throws Exception {
        BigDecimal minamount = prodchargesfinal.getMinamount();
        BigDecimal maxamount = prodchargesfinal.getMaxamount();

        if (minamount.compareTo(maxamount) >= 0) {
            throw new GeneralException("GENE-0040", "EL MONTO MÍNIMO DEBE SER MENOR AL MONTO MÁXIMO EN {0}", "[CARGOS POR SUBPRODUCTO]");
        }

        for (int i = index; i < listSubProductChargesFinal.size(); i++) {
            TgeneSubProductCharges prodcharges = listSubProductChargesFinal.get(i);

            if (prodchargesfinal.equalsWithoutSequence(prodcharges)) {
                BigDecimal minamountcmp = prodcharges.getMinamount();
                BigDecimal maxamountcmp = prodcharges.getMaxamount();

                if (((minamount.compareTo(maxamountcmp) <= 0) && (minamount.compareTo(minamountcmp) >= 0))
                        || ((minamount.compareTo(minamountcmp) >= 0) && (maxamount.compareTo(maxamountcmp) <= 0))
                        || ((minamount.compareTo(minamountcmp) <= 0) && (maxamount.compareTo(maxamountcmp) >= 0))
                        || ((maxamount.compareTo(minamountcmp) >= 0) && (maxamount.compareTo(maxamountcmp) <= 0))) {
                    throw new GeneralException("GENE-0041", "LOS VALORES PARA EL TIPO DE BALANCE {0} SE SOBREPONEN EN {1}", prodchargesfinal.getPk()
                            .getBalancetype(), "[CARGOS POR SUBPRODUCTO]");
                }
            }
            prodcharges = null;
        }
    }

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

}
