package crypto.r35157.cauldron.afets.ticker;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MEXCTicker {
    public MEXCTicker() {
        tickerMap = new HashMap<>();
        client = HttpClient.newHttpClient();

        gson = new GsonBuilder()
                .registerTypeAdapter(MEXCTickerItem.class, new MEXCTickerDeserializer())
                .create();

        request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .GET()
                .build();
    }

    public void updateAll() throws Exception {
        HttpResponse<String> httpResp = client.send(request, HttpResponse.BodyHandlers.ofString());
        String tickerJson = httpResp.body();
        FuturesTickerResponse tickerResp = gson.fromJson(tickerJson, FuturesTickerResponse.class);
        List<MEXCTickerItem> tickerItems = tickerResp.data();

        for (MEXCTickerItem item : tickerItems) {
            tickerMap.put(item.symbol(), item);
        }
    }

    public @Nullable MEXCTickerItem getPrice(@NotNull String symbol) {
        MEXCTickerItem item = tickerMap.get(symbol);
        return item;
    }

    public Set<String> getAllSymbols() {
        return tickerMap.keySet();
    }

    private static final String API_URL = "https://contract.mexc.com/api/v1/contract/ticker";

    private final HttpClient client;
    private final HttpRequest request;
    private final Map<String, MEXCTickerItem> tickerMap;
    private final Gson gson;
}
