/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.cryptolib.commons.utils.serialization;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Base64;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Class is used by {@link ObjectMapper} (and other chained
 * {@link JsonDeserializer}s too) to deserialize Objects by {@link BigInteger}
 * type from JSON, using provided {@link JsonParser}.
 */
public class BigIntegerDeserializer extends JsonDeserializer<BigInteger> {

    @Override
    public BigInteger deserialize(JsonParser jsonParser,
            DeserializationContext context) throws IOException {

        String text = jsonParser.getText().trim();
        if (text.length() == 0) {
            return null;
        } else {
            try {
                return new BigInteger(Base64.getDecoder().decode(text));
            } catch (IllegalArgumentException var6) {
                throw context.weirdStringException(text, BigInteger.class,
                    "not a valid representation");
            }
        }
    }
}
