package network;

import java.io.IOException;
import java.io.ObjectInputStream;

import network.protocol.Packet;

public class ConnexionThread extends Thread {

	private final Connexion connexion;
	private final ObjectInputStream objectInputStream;

	public ConnexionThread(Connexion connexion) throws IOException {
		this.connexion = connexion;
		this.objectInputStream = new ObjectInputStream(this.connexion.socket.getInputStream());
	}

	@Override
	public void run() {
		while (!interrupted()) {
			try {
				// System.out.println(objectInputStream.available());
				Object o = objectInputStream.readObject();
				if (o instanceof Packet packet) {
					connexion.visit(packet);
				}
			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
				this.connexion.close();
				break;
			}
		}
	}

	public void cancel() {
		try {
			objectInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		interrupt();
	}

}
