package cz.moneta.test.dsl.util.task.ods;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.ods.OdsEndpoint;
import cz.moneta.test.harness.exception.HarnessException;
import org.jooq.Record;
import org.jooq.Result;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class OdsTasks {

    private final StoreAccessor harness;

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

    private static String readSqlFromFile(String path) {
        try {
            try (InputStream file = OdsTasks.class.getClassLoader().getResourceAsStream(path)) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(file))) {
                    return reader.lines().collect(Collectors.joining(System.lineSeparator()));
                }
            }
        } catch (NullPointerException | IOException e) {
            throw new HarnessException("Failed to read SQL select: " + path);
        }
    }

    public Result<Record> getCardInfo(String rc) {
        String sql = readSqlFromFile("ods/ods_card_info.sql")
                .replaceAll("#rc_num", rc);
        return harness.getEndpoint(OdsEndpoint.class)
                .executeSql(sql);
    }

    public Result<Record> findIco(String ico) {
        String sql = readSqlFromFile("ods/ods_albertina_find_ico.sql")
                .replaceAll("#ICO", ico);
        return harness.getEndpoint(OdsEndpoint.class)
                .executeSql(sql);
    }

    public Result<Record> findInstPt(String ico, String srcSysId) {
        String sql = readSqlFromFile("ods/ods_inst_pt_info.sql").replaceAll("#ICO", ico).replaceAll("#SRC_SYS_ID", srcSysId);
        return harness.getEndpoint(OdsEndpoint.class)
                .executeSql(sql);
    }
}
