package it.polimi.ingsw.gc14.Network.TCP.Client;

import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer;

import java.io.*;
import java.net.*;

public class TCPClient implements Serializable{
    Socket communicationSocket = null;
    ObjectInputStream socketReceive;
    ObjectOutputStream socketSend;

    GameController controller;
    String hostname;
    int port;

    public TCPClient(GameController controller, String hostname, int port){
        this.controller = controller;
        this.hostname = hostname;
        this.port = port;
    }

    public boolean start(String user, int players){
        try{
            communicationSocket = new Socket(hostname, port);
            socketSend = new ObjectOutputStream(communicationSocket.getOutputStream());
            socketReceive = new ObjectInputStream(communicationSocket.getInputStream());

            socketSend.writeObject(new AddPlayer(user, players));
            if(communicationSocket.getInputStream().read() == -1){
                return false;
            }
            else{
                Thread listener = new Thread(() -> ReceiveMessage());
                listener.start();
                return true;
            }
        }
        catch(Exception e){
            return false;
        }
    }

    private void ReceiveMessage(){
        while(true){
            try{
                Object read = socketReceive.readObject();

                if (read  instanceof NetworkEvent) {    //TODO non fare con instanceof
                    NetworkEvent event = (NetworkEvent) read;
                    if(event.getIsError()) {
                        System.out.println(event.toString());
                    } else {
                        event.apply(controller);
                        //clientController.view.update();           TODO
                    }
                }
                else if (read  instanceof Game) {
                    controller.setModel((Game) read);
                }

            }
            catch(IOException e){
                e.printStackTrace();
            }
            catch(ClassNotFoundException e){
                throw new RuntimeException(e);
            }
            return;
        }
    }

    private void SendEvent(NetworkEvent event){
        try{
            socketSend.writeObject(event);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}
