package com.lithium.rdbi;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.concurrent.NotThreadSafe;

@NotThreadSafe
public class JedisHandle implements AutoCloseable {

    private final JedisPool pool;
    private final Jedis jedis;
    private JedisWrapperDoNotUse jedisWrapper;

    private final ProxyFactory proxyFactory;

    public JedisHandle(JedisPool pool, Jedis jedis, ProxyFactory proxyFactory) {
        this.pool = pool;
        this.jedis = jedis;
        this.proxyFactory = proxyFactory;
    }

    public Jedis jedis() {

        if (jedisWrapper == null) {
            jedisWrapper = proxyFactory.attachJedis(jedis);
        }

        return jedisWrapper;
    }

    public <T> T attach(Class<T> type) {
        return proxyFactory.attach(jedis(), type);
    }

    @Override
    public void close() {

        try {
            if (jedisWrapper.__rdbi_isJedisBusted__()) {
                pool.returnBrokenResource(jedis);
            } else {
                pool.returnResource(jedis);
            }
        } catch (ClassCastException e) {
        }
    }
}

@@ -142,16 +142,42 @@
 eadSafe;
+%0Aimport java.io.Closeable;
 %0A%0A@NotTh
@@ -225,12 +225,8 @@
 nts 
-Auto
 Clos
@@ -345,16 +345,52 @@
 Wrapper;
+%0A    private boolean closed = false;
 %0A%0A    pr
@@ -920,24 +920,77 @@
  close() %7B%0A%0A
+        if (closed) %7B%0A            return;%0A        %7D%0A%0A
         try 
@@ -1214,24 +1214,154 @@
 eption e) %7B%0A
+            //internal error%0A        %7D finally %7B%0A            //for indempotency of Closeable interface%0A            closed = true;%0A
         %7D%0A  

switch from autoclosable of java 7 to closable of java 6