package com.eco.common.mapper.config;

import com.eco.common.mapper.core.FieldMapperInterface;
import com.eco.common.mapper.core.handler.FieldMapperBeanSerializerModifier;
import com.eco.common.mapper.core.handler.FieldMapperHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.eco.common.mapper.annotation.FieldMapperType;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: FieldMapper配置类
 * @Author: GaoKun Wang
 * @Date: 2024/7/1
 */
@Slf4j
@AutoConfiguration
public class FieldMapperConfig {

    @Autowired
    private List<FieldMapperInterface<?>> list;

    @Autowired
    private ObjectMapper objectMapper;

    @PostConstruct
    public void init() {
        Map<String, FieldMapperInterface<?>> map = new HashMap<>(list.size());
        for (FieldMapperInterface<?> trans : list) {
            if (trans.getClass().isAnnotationPresent(FieldMapperType.class)) {
                FieldMapperType annotation = trans.getClass().getAnnotation(FieldMapperType.class);
                map.put(annotation.type(), trans);
            } else {
                log.warn(trans.getClass().getName() + " 翻译实现类未标注 FieldMapperType 注解!");
            }
        }
        FieldMapperHandler.FIELD_MAPPER.putAll(map);
        // 设置 Bean 序列化修改器
        objectMapper.setSerializerFactory(
            objectMapper.getSerializerFactory()
                .withSerializerModifier(new FieldMapperBeanSerializerModifier()));
    }
}
