package de.avatic.taric.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import de.avatic.taric.model.Description;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class DescSetSerializer extends JsonSerializer<Set<Description>> {

    private static final ThreadLocal<String> LANGUAGE_CONTEXT = new ThreadLocal<>();

    public static void setLanguage(String language) {
        LANGUAGE_CONTEXT.set(language);
    }

    public static void clearLanguage() {
        LANGUAGE_CONTEXT.remove();
    }

    @Override
    public void serialize(Set<Description> value, JsonGenerator gen, SerializerProvider serializer) throws IOException {
        if (value != null) {
            var filtered = value;

            String language = LANGUAGE_CONTEXT.get();
            if (language != null) {
                filtered = value.stream()
                        .filter(desc -> language.equalsIgnoreCase(desc.getLang()))
                        .collect(Collectors.toSet());
            }

            if (filtered.isEmpty()) {
                filtered = value.stream()
                        .filter(desc -> "EN".equalsIgnoreCase(desc.getLang()))
                        .collect(Collectors.toSet());
            }

            if(filtered.size() == 1)
                gen.writeObject(filtered.iterator().next());
            else
                gen.writeObject(filtered);
        } else {
            gen.writeNull();
        }
    }
}
