package cz.moneta.test.dsl.udebs;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.udebs.UdebsEndpoint;
import org.jooq.Record;
import org.jooq.Result;

import java.util.concurrent.TimeUnit;

public class PaymentOrder {
    private final StoreAccessor harness;

    private String PAYMENT_ORDERS_DOMESTIC = "SELECT * FROM PAYMENTORDERSDOMESTIC \n" +
            "WHERE DEBITACCOUNTID LIKE '%%%s' " +
            "ORDER BY PACKAGEID DESC";

    private String FOREIGN_PAYMENT_ORDERS = "SELECT * FROM PAYMENTORDERSFOREIGN \n" +
            "WHERE DEBITACCOUNTID='%s' " +
            "ORDER BY PACKAGEID DESC";

    public PaymentOrder(StoreAccessor harness) {
        this.harness = harness;
    }

    private Result<Record> executeSqlPaymentOrdersDomestic(String sqlQuery, String... args) {
        return harness.getEndpoint(UdebsEndpoint.class)
                .executeSql(String.format(sqlQuery, args));
    }

    private Result<Record> executeSqlPaymentOrdersForeign(String sqlQuery, String... args) {
        return harness.getEndpoint(UdebsEndpoint.class)
                .executeSql(String.format(sqlQuery, args));
    }

    public String getAmountOfLastPaymentOrderDomestic(long waitForResponseInSeconds, String accountId) {
        try {
            TimeUnit.SECONDS.sleep(waitForResponseInSeconds);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        return executeSqlPaymentOrdersDomestic(PAYMENT_ORDERS_DOMESTIC, accountId)
                .getValues("AMOUNT")
                .get(0)
                .toString()
                .replace(".", ",");
    }

    public double getAmountOfLastForeignPaymentOrder(long waitForResponseInSeconds, String accountId) {
        try {
            TimeUnit.SECONDS.sleep(waitForResponseInSeconds);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        String amount = executeSqlPaymentOrdersForeign(FOREIGN_PAYMENT_ORDERS, accountId)
                .getValues("AMOUNT")
                .get(0)
                .toString();

        return Double.valueOf(amount);
    }
}
