package network;

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

import network.protocol.Packet;
import network.protocol.PacketVisitor;

public abstract class Connexion implements PacketVisitor {
	
	final Socket socket;
	private final ObjectOutputStream objectOutputStream;
	private final ConnexionThread connexionThread;

	public Connexion(Socket socket) throws IOException {
		this.socket = socket;
		this.objectOutputStream = new ObjectOutputStream(this.socket.getOutputStream());
		this.connexionThread = new ConnexionThread(this);
		this.connexionThread.start();
	}

	public boolean isClosed() {
		return this.socket.isClosed();
	}

	public synchronized void sendPacket(Packet packet) {
		try {
			objectOutputStream.writeObject(packet);
			objectOutputStream.flush();
		} catch (IOException e) {
			System.err.println("Error while sending packet ! " + e.getLocalizedMessage());
			close();
		}
	}

	public void close() {
		this.connexionThread.cancel();
	}
}
