package cn.iocoder.yudao.module.iot.controller.admin.device.enums;

/**
 * Java 基本类型对应 TDengine 列类型枚举
 */
public enum JavaToTdengineTypeEnum {

    BYTE("byte", "TINYINT") {
        @Override
        public Object convertValue(String value) {
            return Byte.parseByte(value);
        }
    },

    SHORT("short", "SMALLINT") {
        @Override
        public Object convertValue(String value) {
            return Short.parseShort(value);
        }
    },

    INT("int", "INT") {
        @Override
        public Object convertValue(String value) {
            return Integer.parseInt(value);
        }
    },

    LONG("long", "BIGINT") {
        @Override
        public Object convertValue(String value) {
            return Long.parseLong(value);
        }
    },

    FLOAT("float", "FLOAT") {
        @Override
        public Object convertValue(String value) {
            return Float.parseFloat(value);
        }
    },

    DOUBLE("double", "DOUBLE") {
        @Override
        public Object convertValue(String value) {
            return Double.parseDouble(value);
        }
    },

    BOOLEAN("boolean", "BOOL") {
        @Override
        public Object convertValue(String value) {
            return Boolean.parseBoolean(value);
        }
    },

    CHAR("char", "NCHAR(1)") {
        @Override
        public Object convertValue(String value) {
            return value.charAt(0);
        }
    };

    private final String javaType;
    private final String tdType;

    JavaToTdengineTypeEnum(String javaType, String tdType) {
        this.javaType = javaType;
        this.tdType = tdType;
    }

    public String getJavaType() {
        return javaType;
    }

    public String getTdType() {
        return tdType;
    }

    /**
     * 每个枚举实现自己的值转换
     */
    public abstract Object convertValue(String value);

    /**
     * 根据 javaType 获取枚举
     */
    public static JavaToTdengineTypeEnum fromJavaType(String javaType) {

        if (javaType == null) {
            return null;
        }

        for (JavaToTdengineTypeEnum e : values()) {

            if (e.javaType.equalsIgnoreCase(javaType)) {
                return e;
            }
        }

        return null;
    }

    /**
     * 根据 javaType 获取 TDengine 类型
     */
    public static String getTdTypeByJavaType(String javaType) {

        JavaToTdengineTypeEnum e = fromJavaType(javaType);

        return e != null ? e.getTdType() : null;
    }

    /**
     * 根据 javaType 转换 value
     */
    public static Object convertValue(String javaType, String value) {

        try {

            JavaToTdengineTypeEnum e = fromJavaType(javaType);

            if (e == null) {
                return Double.parseDouble(value);
            }

            return e.convertValue(value);

        } catch (Exception ex) {

            throw new RuntimeException(
                    "数据类型转换失败: javaType=" + javaType + ", value=" + value, ex
            );
        }
    }
}
