package cn.fateverse.query.submeter.preparestatement;

import cn.fateverse.query.submeter.executor.ForceExecuteCallback;
import cn.fateverse.query.submeter.executor.ForceExecuteTemplate;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

@RequiredArgsConstructor
public abstract class AbstractStatementAdapter extends AbstractUnsupportedOperationStatement {

    private final Class<? extends Statement> targetClass;

    private boolean closed;

    private boolean poolable;

    private int fetchSize;

    private final ForceExecuteTemplate<Statement> forceExecuteTemplate = new ForceExecuteTemplate<>();


    @Getter
    private final List<Statement> statements = new LinkedList<>();

    @SuppressWarnings("unchecked")
    @Override
    public final void close() throws SQLException {
        closed = true;
        try {
            forceExecuteTemplate.execute(statements, new ForceExecuteCallback<Statement>() {

                @Override
                public void execute(final Statement statement) throws SQLException {
                    statement.close();
                }
            });
        } finally {
            statements.clear();
        }
    }

    @Override
    public final boolean isClosed() {
        return closed;
    }

    @Override
    public final boolean isPoolable() {
        return poolable;
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void setPoolable(final boolean poolable) throws SQLException {
        this.poolable = poolable;
        forceExecuteTemplate.execute(statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.setPoolable(poolable);
            }
        });
    }

    @Override
    public final int getFetchSize() {
        return fetchSize;
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void setFetchSize(final int rows) throws SQLException {
        this.fetchSize = rows;
//        statements.forEach(statement -> {
//            try {
//                statement.setFetchSize(rows);
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            }
//        });
//        recordMethodInvocation(targetClass, "setFetchSize", new Class[] {int.class}, new Object[] {rows});
        forceExecuteTemplate.execute(statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.setFetchSize(rows);
            }
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void setEscapeProcessing(final boolean enable) throws SQLException {
        forceExecuteTemplate.execute(statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.setEscapeProcessing(enable);
            }
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void cancel() throws SQLException {
        forceExecuteTemplate.execute(statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.cancel();
            }
        });
    }

    @Override
    public final int getUpdateCount() throws SQLException {
        if (isAccumulate()) {
            return accumulate();
        } else {
            Collection<? extends Statement> statements = this.statements;
            if (0 == statements.size()) {
                return -1;
            }
            return this.statements.iterator().next().getUpdateCount();
        }
    }

    private int accumulate() throws SQLException {
        long result = 0;
        boolean hasResult = false;
        for (Statement each : this.statements) {
            int updateCount = each.getUpdateCount();
            if (updateCount > -1) {
                hasResult = true;
            }
            result += updateCount;
        }
        if (result > Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;
        }
        return hasResult ? Long.valueOf(result).intValue() : -1;
    }

    @Override
    public final SQLWarning getWarnings() {
        return null;
    }

    @Override
    public final void clearWarnings() {
    }

    @Override
    public final boolean getMoreResults() throws SQLException {
        boolean result = false;
        for (Statement each : this.statements) {
            result = each.getMoreResults();
        }
        return result;
    }

    @Override
    public final boolean getMoreResults(final int current) {
        return false;
    }

    @Override
    public final int getMaxFieldSize() throws SQLException {
        return this.statements.isEmpty() ? 0 : this.statements.iterator().next().getMaxFieldSize();
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void setMaxFieldSize(final int max) throws SQLException {
//        recordMethodInvocation(targetClass, "setMaxFieldSize", new Class[] {int.class}, new Object[] {max});
        forceExecuteTemplate.execute(this.statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.setMaxFieldSize(max);
            }
        });
    }

    // TODO Confirm MaxRows for multiple databases is need special handle. eg: 10 statements maybe MaxRows / 10
    @Override
    public final int getMaxRows() throws SQLException {
        return this.statements.isEmpty() ? -1 : this.statements.iterator().next().getMaxRows();
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void setMaxRows(final int max) throws SQLException {
//        recordMethodInvocation(targetClass, "setMaxRows", new Class[] {int.class}, new Object[] {max});
        forceExecuteTemplate.execute(this.statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.setMaxRows(max);
            }
        });
    }

    @Override
    public final int getQueryTimeout() throws SQLException {
        return this.statements.isEmpty() ? 0 : this.statements.iterator().next().getQueryTimeout();
    }

    @SuppressWarnings("unchecked")
    @Override
    public final void setQueryTimeout(final int seconds) throws SQLException {

//        recordMethodInvocation(targetClass, "setQueryTimeout", new Class[] {int.class}, new Object[] {seconds});
        forceExecuteTemplate.execute(this.statements, new ForceExecuteCallback<Statement>() {

            @Override
            public void execute(final Statement statement) throws SQLException {
                statement.setQueryTimeout(seconds);
            }
        });
    }

    protected abstract boolean isAccumulate();

}

