package ttk;

import javax.xml.bind.DatatypeConverter;
import java.net.*;
import java.io.*;
import java.util.Arrays;

public class Session {
    public static final int maxTTKBufSize = 65000;

    String address;
    int port;

    public Socket socket;

    public Session(String address, int port) {
        this.address = address;
        this.port = port;
    }

    public boolean connect() throws IOException {
        socket = new Socket(address, port);

        if (socket.isConnected())
            return true;
        else
            return false;
    }

    public boolean isClosed() {
        if(socket == null)
            return false;

        return socket.isClosed();
    }

    public void disconnect() throws IOException {
        socket.close();
    }

    public Buffer readBufFromSocket() throws IOException {
        Buffer ttk_buf = null;

        byte[] byte_buf = new byte[maxTTKBufSize];

        int bytesRead = socket.getInputStream().read(byte_buf, 0, 2);

        if (bytesRead == 2) {
            int bufferlen = Buffer.deserializeTTKLength(Arrays.copyOf(byte_buf, 2));
            bytesRead = socket.getInputStream().read(byte_buf, 2, bufferlen);

            //debug info
            System.out.println(DatatypeConverter.printHexBinary(Arrays.copyOf(byte_buf, bytesRead + 2)));
            //
            ttk_buf = new Buffer(Arrays.copyOf(byte_buf, bytesRead + 2));
        }

        return ttk_buf;
    }

    public void writeBufferToSocket(Buffer buffer) throws IOException {
        byte[] commandArray = buffer.makeFrame();

        socket.getOutputStream().write(commandArray, 0, commandArray.length);

        //debug info
        System.out.println(DatatypeConverter.printHexBinary(commandArray));
        //
    }
}
