package visualiser.Controllers;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import mock.app.Event;
import mock.exceptions.EventConstructionException;
import shared.exceptions.InvalidBoatDataException;
import shared.exceptions.InvalidRaceDataException;
import shared.exceptions.InvalidRegattaDataException;
import shared.exceptions.XMLReaderException;
import visualiser.model.RaceConnection;

import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Controller for Hosting a game.
 */
public class HostController extends Controller {


    @FXML
    TextField gameNameField;

    @FXML
    TextField hostNameField;

    @FXML
    AnchorPane hostWrapper;


    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

    /**
     * Hosts a game
     * @throws IOException if socket cannot be connected to
     */
    public void hostGamePressed() throws IOException{
        try {
            Event game = new Event(false);
            game.start();
            connectSocket("localhost", 4942);
        } catch (EventConstructionException e) {
            Logger.getGlobal().log(Level.SEVERE, "Could not create Event.", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Connect to a socket
     * @param address address of the server
     * @param port port that the server is run off
     */
    public void connectSocket(String address, int port) {
        try{
            Socket socket = new Socket(address, port);
            hostWrapper.setVisible(false);
            parent.enterLobby(socket);
        } catch (IOException e) { /* Never reached */ }
    }

    public AnchorPane startWrapper(){
        return hostWrapper;
    }

    /**
     * Hosts a game.
     */
    public void hostGame(){
        hostWrapper.setVisible(true);
    }

}
