package com.zhiqiyun.open.mybatis.paginator;


import com.zhiqiyun.open.mybatis.paginator.dialect.Dialect;
import com.zhiqiyun.open.mybatis.paginator.domain.PageBounds;
import com.zhiqiyun.open.mybatis.paginator.support.PropertiesHelper;
import com.zhiqiyun.open.mybatis.paginator.support.SQLHelp;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.*;


/**
 * 为MyBatis提供基于方言(Dialect)的分页查询的插件
 * <p>
 * 将拦截Executor.query()方法实现分页方言的插入.
 *
 * @author badqiu
 * @author miemiedev
 */
@Slf4j
@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class PaginationInterceptor implements Interceptor {
    public static ExecutorService Pool;
    private static final int MAPPED_STATEMENT_INDEX = 0;
    private static final int PARAMETER_INDEX = 1;
    private static final int ROWBOUNDS_INDEX = 2;
    String dialectClass;
//    boolean asyncTotalCount = false;

    @Override
    public Object intercept(final Invocation invocation) throws Throwable {
        final Executor executor = (Executor) invocation.getTarget();
        final Object[] queryArgs = invocation.getArgs();
        final MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
        final Object parameter = queryArgs[PARAMETER_INDEX];
        final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];

        if (rowBounds instanceof PageBounds) {
            PageBounds bounds = (PageBounds) rowBounds;

            if (bounds.getOffset() == RowBounds.NO_ROW_OFFSET && bounds.getLimit() == RowBounds.NO_ROW_LIMIT && bounds.getOrders().isEmpty()) {
                return invocation.proceed();
            }

            final Dialect dialect;
            try {
                Class<?> clazz = Class.forName(dialectClass);
                Constructor<?> constructor = clazz.getConstructor(MappedStatement.class, Object.class, PageBounds.class);
                dialect = (Dialect) constructor.newInstance(new Object[]{ms, parameter, bounds});
            } catch (Exception e) {
                throw new ClassNotFoundException("Cannot create dialect instance: " + dialectClass, e);
            }

            final BoundSql boundSql = ms.getBoundSql(parameter);

            queryArgs[MAPPED_STATEMENT_INDEX] = copyFromNewSql(ms, boundSql, dialect.getPageSQL(), dialect.getParameterMappings(), dialect.getParameterObject());
            queryArgs[PARAMETER_INDEX] = dialect.getParameterObject();
            queryArgs[ROWBOUNDS_INDEX] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);

            Future<Object> listFuture = call(invocation::proceed);


            Callable<Integer> totalCountTask = () -> {
                Integer totalCount;
                Cache cache = ms.getCache();
                if (cache != null && ms.isUseCache() && ms.getConfiguration().isCacheEnabled()) {
                    CacheKey cacheKey = executor.createCacheKey(ms, parameter, new PageBounds(), copyFromBoundSql(ms, boundSql, dialect.getCountSQL(), boundSql.getParameterMappings(), boundSql.getParameterObject()));
                    totalCount = (Integer) cache.getObject(cacheKey);
                    if (totalCount == null) {
                        totalCount = SQLHelp.getCount(ms, executor.getTransaction(), parameter, boundSql, dialect);
                        cache.putObject(cacheKey, totalCount);
                    }
                } else {
                    totalCount = SQLHelp.getCount(ms, executor.getTransaction(), parameter, boundSql, dialect);
                }
                return totalCount;
            };
            Future<Integer> totalCountFuture = call(totalCountTask);
            bounds.setTotal(totalCountFuture.get());

            return listFuture.get();

        }
        return invocation.proceed();
    }

    private <T> Future<T> call(Callable<T> callable) {
        FutureTask<T> future = new FutureTask<>(callable);
        future.run();
        return future;
    }

    private MappedStatement copyFromNewSql(MappedStatement ms, BoundSql boundSql, String sql, List<ParameterMapping> parameterMappings, Object parameter) {
        BoundSql newBoundSql = copyFromBoundSql(ms, boundSql, sql, parameterMappings, parameter);
        return copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
    }

    private BoundSql copyFromBoundSql(MappedStatement ms, BoundSql boundSql, String sql, List<ParameterMapping> parameterMappings, Object parameter) {
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, parameterMappings, parameter);
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        return newBoundSql;
    }

    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        Builder builder = new Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());

        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }

        //setStatementTimeout()
        builder.timeout(ms.getTimeout());

        //setStatementResultMap()
        builder.parameterMap(ms.getParameterMap());

        //setStatementResultMap()
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());

        //setStatementCache()
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        PropertiesHelper propertiesHelper = new PropertiesHelper(properties);
        String dialectClass = propertiesHelper.getRequiredString("dialectClass");
        setDialectClass(dialectClass);
        setPoolMaxSize(propertiesHelper.getInt("poolMaxSize", 0));

    }

    public void setDialectClass(String dialectClass) {
        log.debug("dialectClass: {} ", dialectClass);
        this.dialectClass = dialectClass;
    }

    public void setPoolMaxSize(int poolMaxSize) {
        if (poolMaxSize > 0) {
            log.debug("poolMaxSize: {} ", poolMaxSize);
            Pool = Executors.newFixedThreadPool(poolMaxSize);
        } else {
            Pool = Executors.newCachedThreadPool();
        }


    }

    public static class BoundSqlSqlSource implements SqlSource {
        BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}
