// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.ResultSet;
import java.sql.SQLException;

import static org.junit.Assert.assertTrue;


public class ResultSetClosingProxy
implements InvocationHandler
{
    private boolean _throwOnClose;
    private boolean _closeCalled;

    public ResultSetClosingProxy setThrowOnClose(boolean value)
    {
        _throwOnClose = value;
        return this;
    }

    public void assertCloseCalled()
    {
        assertTrue("close not called", _closeCalled);
    }

    public ResultSet toStub()
    {
        return (ResultSet)Proxy.newProxyInstance(
                        this.getClass().getClassLoader(),
                        new Class[] { ResultSet.class },
                        this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        if (method.getName().equals("close"))
        {
            _closeCalled = true;
            if (_throwOnClose)
                throw new SQLException("proxy threw on close");
            else
                return null;
        }
        throw new UnsupportedOperationException(method.getName());
    }
}
