
package crypto.r35157.cauldron.afets.fundingrate;

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;

public class MEXCFundingRates {
    public MEXCFundingRates() {
        fundingRateMap = new HashMap<>();
        client = HttpClient.newHttpClient();

        gson = new GsonBuilder()
                .registerTypeAdapter(MEXCFundingRateItem.class, new MEXCFundingRatesDeserializer())
                .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 fundingFeeJson = httpResp.body();

        List<MEXCFundingRateItem> fundingRateItems = mapFundingRates(fundingFeeJson);
        refreshLocalFundingRateMap(fundingRateItems);
    }

    private void refreshLocalFundingRateMap(List<MEXCFundingRateItem> fundingRateItems) {
        fundingRateMap.clear();
        for(MEXCFundingRateItem item : fundingRateItems) {
            fundingRateMap.put(item.symbol(), item);
        }
    }

    private List<MEXCFundingRateItem> mapFundingRates(String json) {
        final FundingRatesResponse response;
        final List<MEXCFundingRateItem> items;

        try {
            response = gson.fromJson(json, FundingRatesResponse.class);
            items = response.data();
        } catch (Exception e) {
            throw e;
        }

        return items;
    }

    public @Nullable MEXCFundingRateItem getFundingRate(@NotNull String localSymbol) {
        MEXCFundingRateItem item = fundingRateMap.get(localSymbol);
        return item;
    }

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

    private final HttpClient client;
    private final HttpRequest request;
    private final Map<String, MEXCFundingRateItem> fundingRateMap;
    private final Gson gson;

}
