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.security.Authority;

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

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

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