package org.jpos.tcpay.acquirer.fiserv;

import org.jpos.iso.ISOException;
import org.jpos.iso.ISOHeader;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOUtil;
import org.jpos.iso.header.BaseHeader;
import org.jpos.iso.packager.ISO87BPackager;
import org.jpos.tcpay.acquirer.JposAcquirerTranslator;
import org.jpos.tcpay.model.IsoAcquirerTerminal;
import org.jpos.util.AppLogger;

import java.util.Map;

public class JposFiservTranslator implements JposAcquirerTranslator {

    private AppLogger logger = new AppLogger();


    int[] SUPPORTED_FIELDS = {2,3,4,5,9,11,12,13,14,22,23,24,25,35,37,38,39,41,42,44,49,54,55,60,62,63};
    @Override
    public ISOMsg toMessage(ISOMsg isoMsg, IsoAcquirerTerminal isoAcquirerTerminal, Map<String, Object> metadata) {
        try {
            ISOMsg  acqRequest = (ISOMsg) isoMsg.clone(SUPPORTED_FIELDS);
            acqRequest.setPackager(new ISO87BPackager());
            if (acqRequest.hasField(2) && acqRequest.hasField(14) ) {
                acqRequest.unset(35);
            }
            acqRequest.setMTI(isoMsg.getMTI());
            acqRequest.setDirection(ISOMsg.OUTGOING);
            if ("000001".equals(isoMsg.getString(3))) {
                acqRequest.set(3, "000000");
            }
            acqRequest.set(41, isoAcquirerTerminal.getTid());
            acqRequest.set(42, isoAcquirerTerminal.getMid());
            //acqRequest.set(24, isoAcquirerTerminal.getNii());

            if (!acqRequest.hasField(62)) {
                acqRequest.set(62, isoMsg.getString(11));
            }
            return acqRequest;
        } catch (ISOException e) {
            logger.exceptionLog(e);
        }

        return null;
    }

    @Override
    public ISOMsg fromMessage(ISOMsg isoMsg, ISOMsg jposRequest, Map<String, Object> metadata) {
        ISOMsg  jposResponse = (ISOMsg) isoMsg.clone(SUPPORTED_FIELDS);
        jposResponse.setPackager(new ISO87BPackager());

        jposResponse.set(41, jposRequest.getString(41));
        jposResponse.set(42, jposRequest.getString(42));
        jposResponse.set(24, jposRequest.getString(24));
        jposResponse.unset(63);
        jposResponse.setHeader(jposRequest.getHeader());

        return jposResponse;
    }
}
