package net.yeputons.spbau.spring2016.torrent;

import net.yeputons.spbau.spring2016.torrent.protocol.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.net.SocketAddress;

public class FirmTorrentConnection implements Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(FirmTorrentConnection.class);
    private final SocketAddress address;
    private TorrentConnection connection;

    public FirmTorrentConnection(SocketAddress address) {
        this.address = address;
        LOG.debug("Created FirmTorrentConnection with address " + address.toString());
    }

    @Override
    public void close() throws IOException {
        if (connection != null) {
            connection.close();
        }
    }

    private void ensureConnection() throws IOException {
        if (connection != null && !connection.getSocket().isClosed()) {
            return;
        }
        if (connection != null) {
            LOG.debug("Reconnecting to " + address.toString());
        }
        try {
            connection = TorrentConnection.connect(address);
        } catch (IOException e) {
            if (connection != null) {
                LOG.warn("Unable to reconnect to " + address.toString(), e);
            } else {
                LOG.warn("Unable to connect to " + address.toString(), e);
            }
            throw e;
        }
    }

    public synchronized <T> T makeRequest(Request<T> r) throws IOException {
        ensureConnection();
        try {
            return connection.makeRequest(r);
        } catch (IOException e) {
            LOG.warn("Caught IOException, closing connection", e);
            connection.close();
            throw e;
        }
    }
}

@@ -1176,32 +1176,60 @@
 OException e) %7B%0A
+            String message;%0A
             if (
@@ -1262,33 +1262,34 @@
             
-LOG.warn(
+message = 
 %22Unable to r
@@ -1314,36 +1314,32 @@
 dress.toString()
-, e)
 ;%0A            %7D 
@@ -1361,25 +1361,26 @@
         
-LOG.warn(
+message = 
 %22Unable 
@@ -1415,20 +1415,16 @@
 String()
-, e)
 ;%0A      
@@ -1441,33 +1441,59 @@
           throw 
-e
+new IOException(message, e)
 ;%0A        %7D%0A    
@@ -1758,46 +1758,258 @@
 tion
-%22
 , 
-e);%0A            connection.close();
+rethrowing exception%22);%0A            try %7B%0A                connection.close();%0A            %7D catch (Exception e1) %7B%0A                LOG.warn(%22Caught IOException while closing connection, suppress%22);%0A                e.addSuppressed(e1);%0A            %7D
 %0A   

make more careful logging and re-throwing * Look out for IOException thrown by connection.close() and suppress it * Do not log re-throwed exception (just the fact about them being caught), they're expected to be fully printed by the caller