package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

import model.Contact;
import model.MessageChat;

public class TCPChat extends Thread{
	
	private ArrayList<MessageChat> listeMessagesRecu;
	private Socket socket; 
	
	
	//connexion faite par un autre user
	public TCPChat(Socket socket) {
		this.socket = socket;
		listeMessagesRecu = new ArrayList<MessageChat>();
		this.start();
	}
	
	//connexion faite par le user
	public TCPChat(Contact user) throws IOException {
		this.socket = new Socket(user.getAddress(), user.getPort());
		listeMessagesRecu = new ArrayList<MessageChat>();
		this.start();
	}
	
	
	@Override
	public void run() {
		BufferedReader in;
		try {
			in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			
			while(true) {			
				try {
					String input = in.readLine();
					MessageChat msgRecu = new MessageChat(this.socket.getInetAddress(), this.socket.getLocalAddress(), this.socket.getPort(), this.socket.getLocalPort(), 0, input);
					listeMessagesRecu.add(msgRecu);
					//if (!msgRecu.getMessage().equals(null)) {
						System.out.println("Message reçu : "+msgRecu.getMessage() );
					//}
				} catch (IOException e) {
					System.out.println("Création et read du in impossible");
					e.printStackTrace();
				}
				
			}
		} catch (IOException e1) {
			System.out.println("pb création in");
			e1.printStackTrace();
		}
	}
	
	public void sendMsg(String message) throws IOException {
		PrintWriter out = new PrintWriter(this.socket.getOutputStream(),true);
		out.println(message);
		System.out.println("Message envoyé : "+message);
	}
	
	
	public MessageChat getMessageRecu() {
		return listeMessagesRecu.remove(0);
	}
	
	
	
	

	public ArrayList<MessageChat> getListeMessagesRecu() {
		return listeMessagesRecu;
	}

	public void setListeMessagesRecu(ArrayList<MessageChat> listeMessagesRecu) {
		this.listeMessagesRecu = listeMessagesRecu;
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	
	
}
