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.BodyParam;
import com.njzscloud.common.http.constant.HttpMethod;
import com.njzscloud.common.http.processor.BodyParamProcessor;

public class BodyParamResolver extends ParamResolver<BodyParam, Tuple2<String, byte[]>> {
    byte[] result = null;
    String contentType;

    public BodyParamResolver() {
        super(BodyParam.class);
    }

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

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

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

        contentType = anno.contentType();
        Class<? extends BodyParamProcessor> processorClazz = anno.processor();
        result = ReflectUtil.newInstance(processorClazz).process(anno, paramName, paramClazz, paramValue);
        return true;
    }
}
