package controller;

import model.Chat;
import model.Msg_Text;
import model.RemoteUser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;

public class ListeningThreadTCPChat extends ListeningThread{
		
	private Socket socket;
	
	/* CONSTRUCTOR OF ListeningThreadTCPConnection
	 * @parametres 
	 * 		@param s : String => nom du thread
	 * 		@param myUser : User => utilisateur utilisant ce thread
	 * @description
	 * 	<p>
	 * 	</p>
	 */
	public ListeningThreadTCPChat(String s,Controller controller,Socket socket) { 
		super(s,controller);
		this.socket=socket;
		// TODO OpenSession si ouverture exterieur
	}
	
	/* run
	 * @description
	 * <p>
	 * 		
	 * </p>
	 */
	public void run() {
			/**** function variables ****/
			BufferedReader in = null;
			String msg = null;
			String input;
			String dateString;
			Date date;
		    Calendar date1=Calendar.getInstance();

		    
		    Chat c = null;
		    
		    
		    try {
				in =new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		    /************         Check rm user information            **********/
		    // check data identification from rm user | TO REMOVE IF !=IP
		    int rmPortTCP = -1;
			try {
				rmPortTCP = Integer.parseInt(in.readLine());
			} catch (NumberFormatException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    RemoteUser rm = new RemoteUser("Unknown",this.socket.getInetAddress(),rmPortTCP);

		    int indexRM = controller.myUser.getActiveUserIndexOf(rm);
		    // Check if rm is identifiable
		    /*System.out.println(rm);
		    for(int i=0;i<controller.myUser.getRemoteUsersList().size();i++) {
		    	System.out.println(controller.myUser.getRemoteUsersList().get(i));
		    }
		    System.out.println(indexRM);*/

		    if(indexRM!=-1) {
		    	rm = controller.myUser.getRemoteUsersList().get(indexRM);
		    	// Check if chat already created
		    	int indexChat = controller.myUser.getChatIndexOf(rm);
		    	if(indexChat!=-1) {
		    		System.out.println("("+this.controller.myUser.getPseudo()+") Session déjà créer, on recupère le chat associé");
		    		c = controller.myUser.getChats().get(indexChat);
		    	}
		    	else {
		    		c=this.controller.openSession(rm);
		    	}
		    	
		    	 /*** listening tcp message from rm until session is close ***/
				
				try {
					String msgToprint;
					while (!(input=in.readLine()).equals("end")/* && c.getActive()*/) {
						System.out.println("("+this.controller.myUser.getPseudo()+") recoit => "+rm.getPseudo()+" : "+input);
						Msg_Text message = new Msg_Text(rm,input);
						c.addMessage(message);
						if(controller.activeChat==c) {
							controller.view.notifyNewMessage("("+message.getDate()+")\n"+c.getRemoteUser().getPseudo()+" : "+input);
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }
		    else {
		    	System.out.println("("+this.controller.myUser.getPseudo()+") Remote User unidentifiable => CLOSING CONNECTION");
		    }
		   
		    
		   

			

	
	}
	
	/* close
	 * @description
	 * <p>
	 * 		ferme le socket d'écoute TCP pour le chat
	 * 		interrupt TCP listening thread pour le chat
	 * </p>
	 */
	public void close() {
		try {
			this.socket.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		System.out.println("End of listing thread UDP ("+this.controller.myUser.getPseudo()+")");
		try {
			this.interrupt();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
