package ru.upos;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Обмен пакетами с хостом авторизации
 */
public class HostConnection {

    private InputStream sin;
    private OutputStream sout;
    private byte[] data;

    public byte[] getData() {
        return data;
    }

    public boolean createSocket(String ipAddress, int ipPort) {
        try {
            Socket socket = new Socket(InetAddress.getByName(ipAddress), ipPort);
            sin = socket.getInputStream();
            sout = socket.getOutputStream();
        } catch (IOException e) {
            // сокет не построен, error
            e.printStackTrace();
            return false;
        }
        // сокет построен, success
        return true;
    }

    public boolean read(int maxLen, long timeout) throws IOException {
        byte[] buf = new byte[maxLen];
        int n;
        long startTime = System.currentTimeMillis();

        do {
            n = sin.read(buf);
        } while (n == 0 && (System.currentTimeMillis() - startTime) < timeout);
        data = new byte[n];
        if (n > 0) {
            System.arraycopy(buf, 0, data, 0, n);
        }
        return (n != 0);
    }

    public void write(byte[] buf) throws IOException {
        sout.write(buf);
    }

    public void closeSocket() throws IOException {
        sin.close();
        sout.close();
    }
}
