package io.oversky524.myhttp;

import java.io.IOException;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by gaochao on 2016/4/11.
 */
public class Connection {
    private static final boolean DEBUG = true;
    private Map<Request, Response> requests = new LinkedHashMap<>();
    private Socket mSocket;
    private long mIdleAt = Long.MAX_VALUE;

    public long idleAt(){ return mIdleAt; }

    public void setIdleAt(long idleAt){ mIdleAt = idleAt; }

    Connection(String host, int port){
        try {
            mSocket = new Socket(host, port);
            mSocket.setSoTimeout(5 * 1000);
            if(DEBUG){
                System.out.println(mSocket + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean shouldClose(long aliveDuration){
        if(mIdleAt == Long.MAX_VALUE) return false;
        if(mIdleAt + aliveDuration <= System.nanoTime()) return true;
        return false;
    }

    public Response put(Request request){
        Response response = new Response();
        requests.put(request, response);
        mIdleAt = Long.MAX_VALUE;
        return response;
    }

    public void release(Request request){
        requests.remove(request);
        if(requests.isEmpty()) mIdleAt = System.nanoTime();
    }

    public Socket getSocket(){ return mSocket; }

    public boolean isIdle(){
        boolean empty = requests.isEmpty();
        /*if(empty){
            mIdleAt =
        }*/
        return empty;
    }

    public void closeSafely(){
        try {
            if(mSocket != null) mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(DEBUG) System.out.println(mSocket + " is closed safely");
    }
}

@@ -76,16 +76,89 @@
 Socket;%0A
+import java.net.SocketException;%0Aimport java.net.SocketTimeoutException;%0A
 import j
@@ -181,16 +181,16 @@
 ashMap;%0A
-
 import j
@@ -1043,16 +1043,30 @@
 noTime()
+ %7C%7C readTest()
 ) return
@@ -1807,32 +1807,32 @@
 ce();%0A        %7D%0A
-
         if(DEBUG
@@ -1889,11 +1889,612 @@
 );%0A    %7D
+%0A%0A    private boolean readTest()%7B%0A        boolean result = false;%0A        try %7B%0A            int readTimeout = mSocket.getSoTimeout();%0A            try %7B%0A                mSocket.setSoTimeout(1);%0A                if(mSocket.getInputStream().read() == -1) result = true;%0A            %7D catch (IOException e) %7B%0A                e.printStackTrace();%0A                result = e instanceof SocketTimeoutException;%0A            %7D finally %7B%0A                mSocket.setSoTimeout(readTimeout);%0A            %7D%0A        %7D catch (SocketException e) %7B%0A            e.printStackTrace();%0A        %7D%0A        return result;%0A    %7D
 %0A%7D%0A

test whether a connection is usable before reusing it