package com.topsunit.query.binding;

import com.huigou.data.domain.query.QueryAbstractRequest;
import com.topsunit.query.annotations.Param;
import net.sf.cglib.beans.BeanGenerator;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Collection;

/**
 * 利用cblib生成QueryRequest对象。
 *
 * @author yonghuan
 */
public class CglibQueryRequestFactory extends AbstractQueryRequestFactory implements QueryRequestFactory {

    @Override
    protected QueryAbstractRequest newInstance(Method method, Object[] args) {
        BeanGenerator queryGenerator = new BeanGenerator();
        queryGenerator.setSuperclass(QueryAbstractRequest.class);
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            Param paramAnnotation = parameter.getAnnotation(Param.class);
            if (paramAnnotation != null) {
                Class parameterType = parameter.getType();
                if (Collection.class.isAssignableFrom(parameterType)) {
                    parameterType = String.class;
                }
                queryGenerator.addProperty(paramAnnotation.value(), parameterType);
            }
        }
        QueryAbstractRequest queryRequest = (QueryAbstractRequest) queryGenerator.create();
        return queryRequest;
    }
}
