package network;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class TCPServer extends Thread{
	
	private ServerSocket socket;
	private InetAddress address;
	private int port;
	private ArrayList<TCPChat> listeConnexions;
	private PropertyChangeSupport support;
	
	public TCPServer(int port, InetAddress address) throws IOException {
		this.port = port;
		this.socket = new ServerSocket(port, 1000, address);
		this.address = address;
		this.listeConnexions = new ArrayList<TCPChat>();
		this.support = new PropertyChangeSupport(this);
		this.start();
	}
	
	
	public void addPropertyChangeListener(PropertyChangeListener pcl){
        this.support.addPropertyChangeListener("session chat demarree",pcl);
    }
	
	@Override
	public void run() {
		Socket link;
		try {
			link = socket.accept();
			TCPChat tcpChat = new TCPChat(link);	
			this.listeConnexions.add(tcpChat);
			this.support.firePropertyChange("session chat demarree", true, false);
		} catch (IOException e) {
			System.out.println("Socket non créé ou non fermé");
			e.printStackTrace();
		}
		
	}

	public InetAddress getAddress() {
		return address;
	}

	public void setAddress(InetAddress address) {
		this.address = address;
	}
	
	public TCPChat getConnexionTCPChat() {
		return this.listeConnexions.remove(0);
	}
	
	public ServerSocket getSocket() {
		return this.socket;
	}
}
