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 MysqlTypeToMetaFieldType {

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

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

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

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

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

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

    LONGTEXT("longtext", MetaFieldTypeEnum.LONG_STR.getCode(), ""),

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

    TINYINT("tinyint", MetaFieldTypeEnum.INT.getCode(), ""),

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

    DATETIME("datetime", MetaFieldTypeEnum.DATE_TIME.getCode(), ""),

    DATE("date", MetaFieldTypeEnum.DATE.getCode(), ""),

    TIME("time", MetaFieldTypeEnum.TIME.getCode(), ""),

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

    LONG_BLOB("longblob", MetaFieldTypeEnum.BYTES.getCode(), "");

    private final String mysqlType;

    private final Integer metaType;

    private final String decimalTemplate;

    MysqlTypeToMetaFieldType(String mysqlType, Integer metaType, String decimalTemplate) {
        this.mysqlType = mysqlType;
        this.metaType = metaType;
        this.decimalTemplate = decimalTemplate;
    }

    public static Integer getMetaType(String mysqlType) {
        for (MysqlTypeToMetaFieldType value : MysqlTypeToMetaFieldType.values()) {
            if (value.getMysqlType().equalsIgnoreCase(mysqlType)) {
                return value.getMetaType();
            }
        }
        return null;
    }

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

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

                String decimalTemplate = value.getDecimalTemplate();

                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 "";
    }

}
