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

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

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

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

    INT("NUMBER", MetaFieldTypeEnum.INT.getCode(), "(11,0)"),

    BIGINT("NUMBER", MetaFieldTypeEnum.BIGINT.getCode(), "(20,0)"),

    DECIMAL("NUMBER", MetaFieldTypeEnum.DECIMAL.getCode(), ""),

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

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

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

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

    LIST("CLOB", MetaFieldTypeEnum.LIST.getCode(), "");

    private final String oracleType;

    private final Integer metaType;

    private final String lengthTemplate;

    OracleTypeToMetaFieldType(String oracleType, Integer metaType, String lengthTemplate) {
        this.oracleType = oracleType;
        this.metaType = metaType;
        this.lengthTemplate = lengthTemplate;
    }

    public static Integer getMetaType(String oracleType) {
        for (OracleTypeToMetaFieldType value : OracleTypeToMetaFieldType.values()) {
            if (value.getOracleType().equalsIgnoreCase(oracleType)) {
                return value.getMetaType();
            }
        }
        return null;
    }

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

    public static String getLengthResult(Integer metaType, Integer fieldLength, Integer decimalLength) {
        for (OracleTypeToMetaFieldType value : OracleTypeToMetaFieldType.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 "";
    }

}
