package seng302;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by cbt24 on 3/05/17.
 */
public class RaceConnection {
    private final StringProperty hostname;
    private final int port;
    private final StringProperty status;

    public RaceConnection(String hostname, int port) {
        this.hostname = new SimpleStringProperty(hostname);
        this.port = port;
        this.status = new SimpleStringProperty("");
        check();
    }

    /**
     * Tries to create a socket to hostname and port, indicates status after test.
     * @return true if socket can connect
     */
    @SuppressWarnings("unused")
    public boolean check() {
        InetSocketAddress i = new InetSocketAddress(hostname.get(), port);
        try (Socket s = new Socket()){
            s.connect(i, 5000);
            status.set("Ready");
            return true;
        } catch (IOException e) {}

        status.set("Offline");
        return false;
    }

    public String getHostname() {
        return hostname.get();
    }

    public StringProperty hostnameProperty() {
        return hostname;
    }

    public int getPort() {
        return port;
    }

    public StringProperty statusProperty() {
        return status;
    }
}
