package fr.titionfire.ffsaf.ws.recv;

import fr.titionfire.ffsaf.data.repository.CompetitionRepository;
import fr.titionfire.ffsaf.domain.entity.CombEntity;
import fr.titionfire.ffsaf.ws.PermLevel;
import io.quarkus.hibernate.reactive.panache.common.WithSession;
import io.quarkus.runtime.annotations.RegisterForReflection;
import io.quarkus.websockets.next.WebSocketConnection;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.hibernate.reactive.mutiny.Mutiny;

import java.util.ArrayList;
import java.util.List;

@WithSession
@ApplicationScoped
@RegisterForReflection
public class RRegister {

    @Inject
    CompetitionRepository competitionRepository;

    @WSReceiver(code = "getRegister", permission = PermLevel.TABLE)
    public Uni<List<CombEntity>> getRegister(WebSocketConnection connection, Object o) {
        ArrayList<CombEntity> combEntities = new ArrayList<>();
        return competitionRepository.find("uuid", connection.pathParam("uuid")).firstResult()
                .call(cm -> Mutiny.fetch(cm.getInsc())
                        .onItem().transformToMulti(Multi.createFrom()::iterable)
                        .call(r -> Mutiny.fetch(r.getCategoriesInscrites()))
                        .map(r -> CombEntity.fromModel(r).addCategoriesInscrites(r.getCategoriesInscrites()))
                        .collect().asList()
                        .invoke(combEntities::addAll))
                .call(cm -> Mutiny.fetch(cm.getGuests())
                        .onItem().transformToMulti(Multi.createFrom()::iterable)
                        .call(r -> Mutiny.fetch(r.getCategoriesInscrites()))
                        .map(r -> CombEntity.fromModel(r).addCategoriesInscrites(r.getCategoriesInscrites()))
                        .collect().asList()
                        .invoke(combEntities::addAll))
                .replaceWith(combEntities);
    }
}
