package fr.titionfire.ffsaf.ws.send;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import io.smallrye.mutiny.Uni;
import io.smallrye.mutiny.unchecked.Unchecked;

import java.util.function.Function;

import static fr.titionfire.ffsaf.net2.Client_Thread.MAPPER;

@RegisterForReflection
public class JsonUni<T> {

    private final Class<T> clazz;
    private final Function<? super T, Uni<?>> mapper;

    public JsonUni(Class<T> clazz, Function<? super T, Uni<?>> mapper) {
        this.clazz = clazz;
        this.mapper = mapper;
    }

    public Uni<?> castAndChain(JsonNode message) throws JsonProcessingException {
        return Uni.createFrom().item(MAPPER.treeToValue(message, clazz)).chain(mapper);
    }

    public Uni<?> castAndError(JsonNode message) throws JsonProcessingException {
        return Uni.createFrom().item((T) null).invoke(Unchecked.consumer(__ -> {
            throw new WSClientError(MAPPER.treeToValue(message, String.class));
        })).chain(mapper);
    }
}
