package controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;

import model.*;
import network.*;

public class Agent {
	private Contact user;
	private UDPInput BIn;
	private UDPOutput BOut;
	private TCPChat TCPSend;
	private TCPServer server;
	private ListeContacts list;
	
	
	public Agent(InetAddress address, int portIn, int portOut) throws IOException {
		this.user = new Contact("", address, portIn);
		this.BIn = new UDPInput(user.getAddress(), portIn);
		this.BOut = new UDPOutput(user, portOut);
		this.server = new TCPServer(user.getPort(), user.getAddress());
		this.TCPSend = new TCPChat(user);
		this.list = ListeContacts.getInstance();
	}

	
	
	//Envoi sur 5001 et reçoit sur 5000
	public void testSendBroadcast() throws IOException, InterruptedException {
		BIn.start();
		MessagePseudo msg = new MessagePseudo(this.user.getAddress(), Tools.getLocalIp(), user.getPort(), 14000, 1, "Michel");
		BOut.send(msg, user.getAddress(), user.getPort());
		Thread.sleep(10);
		MessagePseudo msgRecu = BIn.getMessage();
		handleMessage(msgRecu);
		MessagePseudo msg2 = new MessagePseudo(this.user.getAddress(), Tools.getLocalIp(), user.getPort(), 14000, 1, "Jacques");
		BOut.send(msg2, user.getAddress(), user.getPort());
		Thread.sleep(10);
		MessagePseudo msgRecu2 = BIn.getMessage();
		handleMessage(msgRecu2);
		MessagePseudo msg3 = new MessagePseudo(this.user.getAddress(), Tools.getLocalIp(), user.getPort(), 14000, 1, "Bob");
		BOut.send(msg3, user.getAddress(), user.getPort());
		Thread.sleep(10);
		MessagePseudo msgRecu3 = BIn.getMessage();
		handleMessage(msgRecu3);
		choisirPseudo("Bob");
		choisirPseudo("Patrick");
	}
	
	
	public void testSendTCP() throws IOException, InterruptedException {
		
		TCPSend.sendMsg("COUCOU");
		Thread.sleep(1000);
		TCPSend.sendMsg("Ca va ?");
		Thread.sleep(1000);
		TCPSend.sendMsg("Non je suis KO");
		Thread.sleep(1000);
		TCPSend.sendMsg("Moi aussi :'(");
		Thread.sleep(1000);
		
	}
	
	public void handleMessage(MessagePseudo msg) {
		if(!list.pseudoExist(msg.getPseudo())) {
			Contact newUser = new Contact(msg.getPseudo(), msg.getAddressSrc(), msg.getPortSrc());
			list.addContact(newUser);
		}
	}
	
	public void choisirPseudo(String pseudo) {
		if(!list.pseudoExist(pseudo)){
			user.setPseudo(pseudo);
			System.out.println("Pseudo set : "+pseudo);
		}else {
			System.out.println("Pseudo déjà utilisé");
		}
	}
	
}
