package ru.yandex.webmaster3.core.util.joda.jackson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;


/**
 * Created by Oleg Bazdyrev on 12/01/2022.
 */
public class BitSetDeserializer extends StdDeserializer<BitSet> {

    public BitSetDeserializer() {
        super(BitSet.class);
    }

    @Override
    public BitSet deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        List<Long> values = new ArrayList<>();
        JsonToken token;
        while (!JsonToken.END_ARRAY.equals(token = jsonParser.nextValue())) {
            if (JsonToken.VALUE_NUMBER_INT.equals(token)) {
                values.add(jsonParser.getLongValue());
            }
        }
        return BitSet.valueOf(values.stream().mapToLong(Long::longValue).toArray());
    }
}
