package com.ace.cache.parser.impl;

import com.ace.cache.parser.ICacheResultParser;
import com.alibaba.fastjson.JSON;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * 转map 有问题
 */
public class DefaultResultParser implements ICacheResultParser {
    public DefaultResultParser() {
    }

    public Object parse(String value, Type type, Class<?>... origins) {
        Object result = null;
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType)type;
            Type rawType = parameterizedType.getRawType();
            if (((Class)rawType).isAssignableFrom(List.class)) {
                result = JSON.parseArray(value, (Class)parameterizedType.getActualTypeArguments()[0]);
            }else if(((Class)rawType).isAssignableFrom(Map.class)) {
                Map transition = JSON.parseObject(value, Map.class);
                transition.forEach((k, v) -> {
                    transition.put(k, JSON.parseObject(value, (Class)parameterizedType.getActualTypeArguments()[1]));
                });
                result = transition;
            }
        } else if (origins == null) {
            result = JSON.parseObject(value, (Class)type);
        } else {
            result = JSON.parseObject(value, origins[0]);
        }

        return result;
    }
}