package com.eshore.gringotts.forest.configuration;

import com.dtflys.forest.converter.text.DefaultTextConverter;
import com.dtflys.forest.utils.StringUtils;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * Forest增强文本类型转换
 *
 * @author lanyuanxiaoyao
 * @date 2024-05-06
 */
@SuppressWarnings("unchecked")
public class EnhanceTextConverter extends DefaultTextConverter {
    private Object convert(byte[] source, Charset charset, String type) throws Exception {
        return convert(StringUtils.fromBytes(source, charset), type);
    }

    private Object convert(String source, String type) throws Exception {
        switch (type) {
            case "boolean":
            case "java.lang.Boolean":
                return Boolean.valueOf(source);
            case "int":
            case "java.lang.Integer":
                return Integer.valueOf(source);
            case "long":
            case "java.lang.Long":
                return Long.valueOf(source);
            case "float":
            case "java.lang.Float":
                return Float.valueOf(source);
            case "double":
            case "java.lang.Double":
                return Double.valueOf(source);
            default:
                throw new Exception("the source may not be primary type");
        }
    }

    @Override
    public <T> T convertToJavaObject(String source, Type targetType) {
        try {
            return (T) convert(source, targetType.getTypeName());
        } catch (Exception e) {
            return super.convertToJavaObject(source, targetType);
        }
    }

    @Override
    public <T> T convertToJavaObject(byte[] source, Class<T> targetType, Charset charset) {
        try {
            return (T) convert(source, charset, targetType.getName());
        } catch (Exception e) {
            return super.convertToJavaObject(source, targetType, charset);
        }
    }

    @Override
    public <T> T convertToJavaObject(byte[] source, Type targetType, Charset charset) {
        try {
            return (T) convert(source, charset, targetType.getTypeName());
        } catch (Exception e) {
            return super.convertToJavaObject(source, targetType, charset);
        }
    }
}
