package com.purui.prims.headless.core.executor;

import com.purui.prims.common.util.ContextUtils;
import com.purui.prims.headless.api.pojo.response.SemanticQueryResp;
import com.purui.prims.headless.core.pojo.Database;
import com.purui.prims.headless.core.pojo.QueryStatement;
import com.purui.prims.headless.core.utils.ComponentFactory;
import com.purui.prims.headless.core.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component("JdbcExecutor")
@Slf4j
public class JdbcExecutor implements QueryExecutor {
    @Override
    public boolean accept(QueryStatement queryStatement) {
        return true;
    }

    @Override
    public SemanticQueryResp execute(QueryStatement queryStatement) {
        // accelerate query if possible
        for (QueryAccelerator queryAccelerator : ComponentFactory.getQueryAccelerators()) {
            if (queryAccelerator.check(queryStatement)) {
                SemanticQueryResp semanticQueryResp = queryAccelerator.query(queryStatement);
                if (Objects.nonNull(semanticQueryResp) && !semanticQueryResp.getResultList().isEmpty()) {
                    log.info("query by Accelerator {}", queryAccelerator.getClass().getSimpleName());
                    return semanticQueryResp;
                }
            }
        }

        SqlUtils sqlUtils = ContextUtils.getBean(SqlUtils.class);
        /** bug
        if (StringUtils.isEmpty(queryStatement.getSourceId())) {
            log.warn("data base id is empty");
            return null;
        }
         */
        log.info("query SQL: {}", queryStatement.getSql());
        Database database = queryStatement.getSemanticModel().getDatabase();
        SemanticQueryResp queryResultWithColumns = new SemanticQueryResp();
        SqlUtils sqlUtil = sqlUtils.init(database);
        sqlUtil.queryInternal(queryStatement.getSql(), queryResultWithColumns);
        queryResultWithColumns.setSql(queryStatement.getSql());
        return queryResultWithColumns;
    }

}
