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

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.EventType;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.concurrent.BlockingQueue;

public class ClientHandler implements Runnable {
    private Socket clientSocket;
    private TCPServer server;
    public ObjectInputStream in = null;
    public ObjectOutputStream out = null;
    List<ClientHandler> clientHandlers;
    BlockingQueue<NetworkEvent> actionQueue;
    private EventType eventType;

    public Socket getClientSocket() {
        return clientSocket;
    }

    public ClientHandler(Socket clientSocket, List<ClientHandler> clientHandlers, BlockingQueue<NetworkEvent> actionQueue) {
        this.clientSocket = clientSocket;
        this.clientHandlers = clientHandlers;
        this.actionQueue = actionQueue;
    }

    @Override
    public void run(){
        clientLoop();
    }

    private void clientLoop(){
        try{
            NetworkEvent input = null;
            synchronized(in){
                in = new ObjectInputStream(clientSocket.getInputStream());
            }
            while(true){
                try{
                    input = (NetworkEvent) (in.readObject());
                    if(!actionQueue.add(input)){
                        System.out.println("An error occurred in inserting an action into queue");
                    }
                }
                catch(java.io.IOException e){
                    e.printStackTrace();
                }
                catch (ClassNotFoundException e){
                    throw new RuntimeException(e);
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void notifyEvent(NetworkEvent event){
        synchronized(out){
            try{
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                out.writeObject(event);
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    public void notifyModel(Game game){
        synchronized(out){
            try{
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                out.writeObject(game);
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }

}


