import java.awt.List;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;  // Import the Scanner class

public class User{
	
	protected InetAddress addIP;
	protected String pseudo;
	protected int nport;
	protected boolean actif;
	
	protected User[] remoteUserList;

	public User(int nport) throws IOException{
		try
		{
			this.addIP = InetAddress.getLocalHost();
		}
		catch(UnknownHostException e) {
			System.out.println("Could not find local address!");
		}
		
		this.nport = nport;
		
		this.setPseudo();
		
		this.actif = true;
		
	}
	
	public User(int nport,String pseudo) {
		try
		{
			this.addIP = InetAddress.getLocalHost();
		}
		catch(UnknownHostException e) {
			System.out.println("Could not find local address!");
		}
		this.pseudo = pseudo;
		this.nport = nport;
		this.actif = true;
	}
	
	
	public InetAddress getAddIP() {
		return addIP;
	}


	public void setAddIP(InetAddress addIP) {
		this.addIP = addIP;
	}


	public String getPseudo() {
		return pseudo;
	}


	public void setPseudo() throws IOException {
	    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
	    System.out.println("Enter pseudo :");
	    String tmpPseudo = myObj.nextLine();  // Read user input

		while(!(this.validatePseudo(tmpPseudo))) {
			System.out.println("Already taken, choose another one :");
		    tmpPseudo = myObj.nextLine();  // Read user input
		}
		
		this.pseudo = tmpPseudo;
	}
	
	public Boolean validatePseudo(String tmpPseudo) throws IOException {
		Boolean valid = true;
		int nbResponseMin = 1;
		
		// Call broadcast 
		InetAddress broadcastIP = InetAddress.getLocalHost(); // change to broadcast
		
		DatagramSocket dgramSocket = new DatagramSocket(2001,addIP);

		byte[] buffer = new byte[256];
		
		DatagramPacket outPacket= new DatagramPacket(tmpPseudo.getBytes(), tmpPseudo.length(),broadcastIP, 2001);

		dgramSocket.send(outPacket);
		
		while(nbResponseMin > 0 && valid) {
			DatagramPacket inPacket= new DatagramPacket(buffer, buffer.length);
			dgramSocket.receive(inPacket);
			buffer = inPacket.getData();
			String listPseudo = new String(buffer);
			System.out.println(listPseudo);
			String[] lstPseudo = listPseudo.split(":");
			ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(lstPseudo));
			valid=stringList.contains(tmpPseudo);
			nbResponseMin--;
		}
		dgramSocket.close();
		
		return valid;
	}


	public int getNport() {
		return nport;
	}


	public void setNport(int nport) {
		this.nport = nport;
	}


	public boolean isActif() {
		return actif;
	}


	public void setActif(boolean actif) {
		this.actif = actif;
	}

	

	public static void main(String[] args) throws IOException {
			User activeUsr1 = new User(2001,"Mike");
			User activeUsr2 = new User(2002,"Sue");
		
			User usr1 = new User(3);
			usr1.setPseudo();
	}
}
