package cn.lihongjie.coal;

import cn.lihongjie.coal.errorMsg.entity.ErrorMsgEntity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CaseFormat;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.TypeSpec;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.util.*;

import javax.lang.model.element.Modifier;

public class DictCodeGen {

    @SneakyThrows
    public static void main(String[] args) {

        ClassPathResource classPathResource = new ClassPathResource("/config/dictionary.json");

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        List<ErrorMsgEntity> errorMsgs;

        try (InputStream inputStream = classPathResource.getInputStream()) {
            errorMsgs = mapper.readValue(inputStream, new TypeReference<List<ErrorMsgEntity>>() {});
        }

        TypeSpec.Builder builder =
                TypeSpec.classBuilder("DictCode")
                        .addModifiers(Modifier.PUBLIC)
                        .addAnnotation(UtilityClass.class);

        for (ErrorMsgEntity errorMsg : errorMsgs) {

            builder.addField(
                    FieldSpec.builder(
                                    String.class,
                                    CaseFormat.LOWER_UNDERSCORE.to(
                                            CaseFormat.UPPER_UNDERSCORE,
                                            errorMsg.getCode().replace(".", "_")),
                                    Modifier.PUBLIC,
                                    Modifier.STATIC,
                                    Modifier.FINAL)
                            .initializer("$S",   errorMsg.getCode() )
                            .build());
        }

        builder.build();


        Codegen.saveFile("cn.lihongjie.coal.common", builder.build());
    }
}
