package com.njzscloud.common.http.resolver;

import cn.hutool.core.util.ReflectUtil;
import com.njzscloud.common.core.tuple.Tuple2;
import com.njzscloud.common.core.utils.Mime;
import com.njzscloud.common.http.annotation.JsonBodyParam;
import com.njzscloud.common.http.constant.HttpMethod;
import com.njzscloud.common.http.processor.JsonBodyParamProcessor;

public class JsonBodyParamResolver extends ParamResolver<JsonBodyParam, Tuple2<String, byte[]>> {
    byte[] result = null;

    public JsonBodyParamResolver() {
        super(JsonBodyParam.class);
    }

    @Override
    public Tuple2<String, byte[]> resolve(HttpMethod httpMethod, String urlTpl) {
        if (result == null) return null;
        return Tuple2.create(Mime.JSON, result);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected boolean resolveParameter(JsonBodyParam anno, String paramName, Class<?> paramClazz, Object paramValue) {
        Class<? extends JsonBodyParamProcessor> processorClazz = anno.processor();
        result = ReflectUtil.newInstance(processorClazz).process(anno, paramName, paramClazz, paramValue);
        return true;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected boolean resolveField(boolean hasParameterAnno, JsonBodyParam anno, String paramName, Class<?> paramClazz, Object paramValue) {
        if (hasParameterAnno) return false;

        Class<? extends JsonBodyParamProcessor> processorClazz = anno.processor();
        result = ReflectUtil.newInstance(processorClazz).process(anno, paramName, paramClazz, paramValue);

        return true;
    }
}
