package com.paritytrading.nassau.soupbintcp.gateway;

import com.paritytrading.nassau.MessageListener;
import com.paritytrading.nassau.moldudp64.MoldUDP64Client;
import com.paritytrading.nassau.soupbintcp.SoupBinTCP;
import com.paritytrading.nassau.soupbintcp.SoupBinTCPServer;
import com.paritytrading.nassau.soupbintcp.SoupBinTCPServerStatusListener;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

class Session implements Closeable, MessageListener, SoupBinTCPServerStatusListener {

    private static SoupBinTCP.LoginAccepted loginAccepted = new SoupBinTCP.LoginAccepted();

    private MoldUDP64Client  upstream;
    private SoupBinTCPServer downstream;

    public Session(UpstreamFactory upstream, SocketChannel downstream) throws IOException {
        this.downstream = new SoupBinTCPServer(downstream, this, this);
        this.upstream   = upstream.create(this.downstream);
    }

    @Override
    public void close() throws IOException {
        upstream.close();
        downstream.close();
    }

    @Override
    public void message(ByteBuffer buffer) throws IOException {
        close();
    }

    @Override
    public void heartbeatTimeout(SoupBinTCPServer session) throws IOException {
        close();
    }

    @Override
    public void loginRequest(SoupBinTCPServer session, SoupBinTCP.LoginRequest payload) throws IOException {
        loginAccepted.session        = payload.requestedSession;
        loginAccepted.sequenceNumber = payload.requestedSequenceNumber;

        downstream.accept(loginAccepted);
    }

    @Override
    public void logoutRequest(SoupBinTCPServer session) throws IOException {
        close();
    }

    public MoldUDP64Client getUpstream() {
        return upstream;
    }

    public SoupBinTCPServer getDownstream() {
        return downstream;
    }

}

@@ -1423,32 +1423,78 @@
 eption %7B%0A       
+ System.arraycopy(payload.requestedSession, 0,
  loginAccepted.s
@@ -1499,24 +1499,34 @@
 .session
+, 0,%0A     
         
 = payloa
@@ -1517,17 +1517,18 @@
         
-=
+  
  payload
@@ -1544,16 +1544,24 @@
 dSession
+.length)
 ;%0A      
@@ -1561,16 +1561,69 @@
 %0A       
+ System.arraycopy(payload.requestedSequenceNumber, 0,
  loginAc
@@ -1643,18 +1643,36 @@
 ceNumber
+, 0,%0A              
  
-=
  payload
@@ -1695,16 +1695,24 @@
 ceNumber
+.length)
 ;%0A%0A     

Fix login request handling in SoupBinTCP gateway