package cn.stylefeng.team.meta.sdk.parser;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.team.meta.api.enums.MetaFieldTypeEnum;
import lombok.Getter;

import java.util.HashMap;

@Getter
public enum PgSqlTypeToMetaFieldType {

    BIGINT("int8", MetaFieldTypeEnum.BIGINT.getCode(), ""),

    VARCHAR("varchar", MetaFieldTypeEnum.NORMAL_STR.getCode(), "({length})"),

    ONE_CHAR("varchar", MetaFieldTypeEnum.FIXED_STR.getCode(), "({length})"),

    TEXT("text", MetaFieldTypeEnum.LONG_STR.getCode(), ""),

    JSON("json", MetaFieldTypeEnum.OBJECT.getCode(), ""),

    LIST("json", MetaFieldTypeEnum.LIST.getCode(), ""),

    INT("int8", MetaFieldTypeEnum.INT.getCode(), ""),

    DECIMAL("numeric", MetaFieldTypeEnum.DECIMAL.getCode(), "({length},{decimal})"),

    DATETIME("timestamp", MetaFieldTypeEnum.DATE_TIME.getCode(), "(6)"),

    DATE("timestamp", MetaFieldTypeEnum.DATE.getCode(), "(6)"),

    TIME("timestamp", MetaFieldTypeEnum.TIME.getCode(), "(6)");

    private final String pgSqlType;

    private final Integer metaType;

    private final String lengthTemplate;

    PgSqlTypeToMetaFieldType(String pgSqlType, Integer metaType, String lengthTemplate) {
        this.pgSqlType = pgSqlType;
        this.metaType = metaType;
        this.lengthTemplate = lengthTemplate;
    }

    public static Integer getMetaType(String pgSqlType) {
        for (PgSqlTypeToMetaFieldType value : PgSqlTypeToMetaFieldType.values()) {
            if (value.getPgSqlType().equalsIgnoreCase(pgSqlType)) {
                return value.getMetaType();
            }
        }
        return null;
    }

    public static String getSqlType(Integer metaType) {
        for (PgSqlTypeToMetaFieldType value : PgSqlTypeToMetaFieldType.values()) {
            if (value.getMetaType().equals(metaType)) {
                return value.getPgSqlType();
            }
        }
        return null;
    }

    public static String getLengthResult(Integer metaType, Integer fieldLength, Integer decimalLength) {
        for (PgSqlTypeToMetaFieldType value : PgSqlTypeToMetaFieldType.values()) {
            if (value.getMetaType().equals(metaType)) {

                String decimalTemplate = value.getLengthTemplate();

                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                if (fieldLength != null) {
                    stringObjectHashMap.put("length", fieldLength);
                }
                if (decimalLength != null) {
                    stringObjectHashMap.put("decimal", decimalLength);
                }

                return StrUtil.format(decimalTemplate, stringObjectHashMap, true);
            }
        }
        return "";
    }

}
