package controller;

import model.LocalUser;

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

public class ListeningThreadTCPConnection extends ListeningThread{
	
	private Socket socket_tcp=null;
	
	/* CONSTRUCTOR OF ListeningThreadTCPConnection
	 * @parametres 
	 * 		@param s : String => nom du thread
	 * 		@param myUser : User => utilisateur utilisant ce thread
	 * @description
	 * 	<p>
	 * 	</p>
	 */
	public ListeningThreadTCPConnection(String s,Controller controller) { 
		super(s,controller);
		
	}
	
	public void accept(ServerSocket servSocket) throws IOException {
		Socket socket_tcp= servSocket.accept();
		ListeningThreadTCPChat threadtcpchat = new ListeningThreadTCPChat("Chat_with_"+controller.myUser.getPseudo(),controller,socket_tcp);
		threadtcpchat.start();
		threadtcpchat.interrupt();
		
	}
	
	/* run
	 * @description
	 * 	<p>
	 * 		écoutes les messages TCP tant que l'utilisateur est actif
	 * 		Traitement
	 * 			Si réception d'une demande, créer un thread pour la conversation
	 *	</p>
	 */
	public void run(){ 
		
		// Tant que l'utilisateur est actif on attends la demande de nouvelle conversation
		ServerSocket servSocket=null;
		try {
			servSocket = new ServerSocket(controller.myUser.getPortTCP());
			System.out.println("("+this.controller.myUser.getPseudo()+") Server is listening on port "+this.controller.myUser.getPortTCP());
		} catch (IOException e) {
			System.out.println("("+this.controller.myUser.getPseudo()+") Server is not listening on port "+this.controller.myUser.getPortTCP());
			e.printStackTrace();
		}
		// TODO changer le true
		while(true) {
			System.out.println("("+this.controller.myUser.getPseudo()+") WAITING FOR NEW CONNECTION");

			try {
				this.accept(servSocket);
				System.out.println("("+this.controller.myUser.getPseudo()+") NEW CONNECTION");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			
		}	
		
	}
	
	/* close
	 * @description
	 * <p>
	 * 		ferme le socket d'écoute TCO
	 * 		interrupt UDP listening threadS
	 * </p>
	 */
	public void close() {
		try {
			this.socket_tcp.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		System.out.println("End of listing thread TCP ("+this.controller.myUser.getPseudo()+")");
		try {
			this.interrupt();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
}


