package top.baogutang.strategy.infra;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import top.baogutang.strategy.commons.enums.Timeframe;
import top.baogutang.strategy.models.Kline;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OkxPublicClient {

    private static final String BASE = "https://www.okx.com";

    private final OkHttpClient http;

    private final ObjectMapper mapper;

    public OkxPublicClient(OkHttpClient http, ObjectMapper mapper) {
        this.http = http;
        this.mapper = mapper;
    }

    public List<Kline> getHistory(String instId, Timeframe tf, int limit) throws IOException {
        String bar;
        switch (tf) {
            case M15:
                bar = "15m";
                break;
            case H1:
                bar = "1H";
                break;
            case H4:
                bar = "4H";
                break;
            default:
                bar = "1H";
        }
        HttpUrl url = HttpUrl.parse(BASE + "/api/v5/market/candles").newBuilder()
                .addQueryParameter("instId", instId)
                .addQueryParameter("bar", bar)
                .addQueryParameter("limit", String.valueOf(limit))
                .build();
        Request req = new Request.Builder().url(url).get().build();
        Response resp = http.newCall(req).execute();
        try {
            if (!resp.isSuccessful()) {
                throw new IOException("HTTP " + resp.code());
            }
            JsonNode root = mapper.readTree(resp.body().string());
            JsonNode data = root.get("data");
            List<Kline> list = new ArrayList<Kline>();
            for (int i = data.size() - 1; i >= 0; i--) {
                JsonNode arr = data.get(i);
                long ts = arr.get(0).asLong();
                double o = arr.get(1).asDouble();
                double h = arr.get(2).asDouble();
                double l = arr.get(3).asDouble();
                double c = arr.get(4).asDouble();
                double v = arr.get(5).asDouble();
                list.add(new Kline(ts, o, h, l, c, v, ts + tf.millis - 1, true));
            }
            return list;
        } finally {
            resp.close();
        }
    }
}
