package com.brilliance.mda.support.jakson.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.math.BigDecimal;

public class BigDecimalSerializeRate  extends JsonSerializer<BigDecimal> implements ContextualSerializer {
    public BigDecimalSerializeRate(){

    }
    private int decimal;
    public BigDecimalSerializeRate(int decimal){
        this.decimal = decimal;
    }

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(null != value ) {
            gen.writeString(value.setScale(decimal, BigDecimal.ROUND_HALF_UP).toPlainString());
        }else {
            gen.writeString("");
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property)
            throws JsonMappingException {
        int decimal = 0;
        DecimalLength ann=null;

        if (property !=null) {
            ann = property.getAnnotation(DecimalLength.class);
        }

        if (ann != null) {
            decimal = ann.value();
        }
        return new BigDecimalSerializeRate(decimal);
    }
}
