package com.topsunit.query.binding;

import com.huigou.data.query.model.QueryDescriptor;
import com.topsunit.query.annotations.Select;
import com.topsunit.query.annotations.Sql;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * 用于获取<sql>标签中的sql语句。
 *
 * @author yonghuan
 * @see Sql
 * @since 1.1.3
 */
class ObtainSqlInvokeStrategy implements InvokeStrategy {

    private final static List<Class> COMPATIBLE_ANNOTATIONS = Arrays.asList(Select.class, Sql.class);

    @Override
    public boolean supports(InvokeContext invokeContext, Method method, Object[] args) {
        return method.getAnnotation(Sql.class) != null;
    }

    @Override
    public Object invoke(InvokeContext invokeContext, Method method, Object[] args) {
        boolean compatible = COMPATIBLE_ANNOTATIONS.stream()
                .filter(c -> method.getAnnotation(c) != null)
                .findAny()
                .isPresent();
        if (!compatible) {
            return null;
        }
        String[] queryNameAndSqlName = method.getName().split("\\$");
        String queryName = queryNameAndSqlName[0];
        String sqlName = queryNameAndSqlName[1];
        QueryDescriptor queryDescriptor = invokeContext.getSqlExecutor().getQuery(invokeContext.getXml(), queryName);
        return queryDescriptor.getSqlByName(sqlName);
    }
}
