package com.sonic.daosupport.mysql;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.sonic.daosupport.wrapper.SimpleWrapperConverter;
import com.google.common.base.Strings;

/**
 * @author code
 */
class MybatisPlusConverterUtils {

    private static Map<Class, SimpleWrapperConverter> converters = new ConcurrentHashMap<>(32);

    public static SimpleWrapperConverter getWrapperConverter(Class entityClass) {
        return converters.computeIfAbsent(entityClass, clazz ->
                SimpleWrapperConverter.builder()
                        .operatorProcessor(new MybatisPlusOperatorProcessor())
                        .fieldColumnMap(getFieldMapping(clazz))
                        .build());
    }

    public static Map<String, String> getFieldMapping(Class clazz) {
        // XXX: TableInfoHelper.getTableInfo(clazz).getFieldList返回的映射关系是不包含@TableId注解（会导致根据id查询的列找不到。）
        //  在获取property和column映射关系的时候，需要聚合filedList和@TableId
        TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
        Map<String, String> fieldMap = tableInfo.getFieldList().stream()
                .collect(Collectors.toMap(TableFieldInfo::getProperty, TableFieldInfo::getColumn));
        if (!Strings.isNullOrEmpty(tableInfo.getKeyProperty())) {
            fieldMap.put(tableInfo.getKeyProperty(), tableInfo.getKeyColumn());
        }
        return fieldMap;
    }
}
