package com.artfess.base.attachment;

import com.artfess.base.annotation.BigDecimalFormat;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

public final class BigDecimalFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<BigDecimalFormat> {

  @Override
  public Set<Class<?>> getFieldTypes() {
    Set<Class<?>> types = new HashSet<Class<?>>() ;
    types.add(Integer.class) ;
    return types;
  }
 
  @Override
  public Printer<BigDecimal> getPrinter(BigDecimalFormat annotation, Class<?> fieldType) {
    return new BigDecimalFormatter() ;
  }
 
  @Override
  public Parser<BigDecimal> getParser(BigDecimalFormat annotation, Class<?> fieldType) {
    return new BigDecimalFormatter() ;
  }

  private class BigDecimalFormatter implements Formatter<BigDecimal> {
    @Override
    public String print(BigDecimal object, Locale locale) {
      if (object == null) {
        return  null;
      }
      return object.stripTrailingZeros().toPlainString();
    }

    @Override
    public BigDecimal parse(String object, Locale locale) {
      if (object == null) {
        return  null;
      }
      return new BigDecimal(object).stripTrailingZeros();
    }
  }
 
}