package com.izouma.nineth.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.izouma.nineth.domain.Tag;
import com.izouma.nineth.security.Authority;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class CollectionTagSerializer extends JsonSerializer<Set<Tag>> {
    @Override
    public void serialize(Set<Tag> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
        } else {
            gen.writeStartArray();
            for (Tag tag : value) {
                gen.writeObject(tag);
            }
            gen.writeEndArray();
        }
    }

    @Override
    public void serializeWithType(Set<Tag> value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
        HashSet<Tag> set = new HashSet<>(value);
        WritableTypeId typeId = typeSer.writeTypePrefix(gen, typeSer.typeId(set, JsonToken.VALUE_STRING));
        gen.writeStartArray();
        for (Tag tag : set) {
            gen.writeObject(tag);
        }
        gen.writeEndArray();
        typeSer.writeTypeSuffix(gen, typeId);
    }
}
