package fr.titionfire.ffsaf.rest.data;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import fr.titionfire.ffsaf.data.model.CompetitionModel;
import fr.titionfire.ffsaf.net2.data.SimpleCompet;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;

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

@Data
@AllArgsConstructor
@RegisterForReflection
public class SimpleCompetData {
    private long id;
    private boolean show_blason;
    private boolean show_flag;
    private List<String> admin;
    private List<String> table;

    public static SimpleCompetData fromModel(SimpleCompet compet) {
        if (compet == null)
            return null;

        return new SimpleCompetData(compet.id(), compet.show_blason(), compet.show_flag(),
                new ArrayList<>(), new ArrayList<>());
    }

    public static SimpleCompetData fromModel(CompetitionModel competitionModel) {
        if (competitionModel == null)
            return null;

        boolean show_blason = true;
        boolean show_flag = false;

        if (competitionModel.getConfig() != null) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(competitionModel.getConfig());

                if (rootNode.has("show_blason"))
                    show_blason = rootNode.get("show_blason").asBoolean();
                if (rootNode.has("show_flag"))
                    show_flag = rootNode.get("show_flag").asBoolean();

            } catch (JsonProcessingException ignored) {
            }
        }

        return new SimpleCompetData(competitionModel.getId(), show_blason, show_flag,
                new ArrayList<>(), new ArrayList<>());
    }

    public String getConfigForInternal(){
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.createObjectNode()
                .put("show_blason", this.show_blason)
                .put("show_flag", this.show_flag);
        try {
            return objectMapper.writeValueAsString(rootNode);
        } catch (JsonProcessingException e) {
            return "{}";
        }
    }
}
