package examples;

import tlv.TlvItem;

/*
 * Для работы со "Спасибо" в настройках терминала должна быть включена настройка:
 * Дополнительные опции -> Возвращать промежуточный код ответа
 * Промежуточный код ответа равен 4353
 */

public class PaymentWithSpasibo {
    public static void main(String[] args) {

        device.Pinpad pp = new device.Pinpad();

        try {
            pp.ttkSession.connect();

            int amount = 34500;
            int amountSpasibo = 12500;

            //pay
            ttk.commands.Command payment = new ttk.commands.Payment(pp, amount);
            ttk.Buffer paymentResult = payment.run();

            //find status code
            TlvItem paymentErrorCode = TlvItem.findItem("TAG_TTK_ERROR_CODE", paymentResult.tagContainer);

            if (new String(paymentErrorCode.getValue()).equals("4353")) {
                //calculate new amount
                ttk.commands.Command paymentComplition = new ttk.commands.Payment(pp, amount - amountSpasibo);

                //extract card hash and insert it in track2
                TlvItem cardHash = TlvItem.findItem("TAG_TTK_HASH", paymentResult.tagContainer);
                paymentComplition.addToContext(new TlvItem(tlv.Tag.findTag("TAG_TTK_TRACK2"), cardHash.getValue()));

                //optional: it's ok to use old ERN and RequestID for the second half of transaction
                paymentComplition.setErn(payment.getErn());
                paymentComplition.setRequestID(payment.getRequestID());

                ttk.Buffer paymentComplitionResult = paymentComplition.run();
            }

            pp.ttkSession.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
