package com.ibeetl.admin.console.util;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ibeetl.admin.core.annotation.ElColumn;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 视图工具类
 *
 * @author 一日看尽长安花
 */
public class VOUtil {

  static final String JSON_PATH_KEY = "json_path";

  /**
   * Method resolveElColumn ... todo 预计重新定义一个类用来转换，而不是用map
   *
   * @param cls
   *     of type Class ，一个专门存放元数据的ElQuery类
   * @return Map
   */
  public static List<Map<String, Object>> resolveElColumn(Class cls) {

    List<Map<String, Object>> metedataList = new ArrayList<>();
    Field[] declaredFields = cls.getDeclaredFields();
    for (Field field : declaredFields) {
      Map<String, Object> elcolumnValMap =
          AnnotationUtil.getAnnotationValueMap(field, ElColumn.class);
      if (MapUtil.isEmpty(elcolumnValMap)) {
        continue;
      }
      Map<String, Object> camelKeyValueMap = elcolumnValMap.entrySet().stream().collect(Collectors
          .toMap(k -> StrUtil.toUnderlineCase(k.getKey()), v -> v.getValue(), (o, n) -> n));
      String camelKey = StrUtil.toUnderlineCase(field.getName());
      camelKeyValueMap
          .compute(JSON_PATH_KEY, (k, v) -> StrUtil.isEmpty(v.toString()) ? camelKey : v);
      camelKeyValueMap.put("key", camelKey);
      metedataList.add(camelKeyValueMap);
    }
    return metedataList.stream()
        .sorted(Comparator.comparing(v -> ((Integer) v.get("order")))).collect(
            Collectors.toList());
  }

}
