package server;

import java.io.*;
import java.util.Vector;

import protocol.Header.MsgType;
import protocol.*;
import chat.*;

public class ServerGestTopics extends TCPServeurMessage implements GestTopics  {

	private GestTopics concretGT ;
	//private GestAuthentification concretGA;
	

	public ServerGestTopics() {
		concretGT = new TCPGestTopics();
		//concretGA = new Authentification();
	}
	

	@Override
	public void gereClient() {
		try {
			System.out.println("Handling new client for GestTopics service");
			
			while (true) {
				int tries = 0;
				Message req;
				try {
					String topic;
					req = getMessage();
					System.out.println("read message :"+req);
					switch (req.head.type) {
					case LISTE_TOPICS :
						sendMessage( new Message(MsgType.LISTE_TOPICS , listerTopics()));
						break;
					case CREATE_TOPIC :
						topic = req.data.get(0);
						creerTopic(topic);
						sendMessage( new Message(MsgType.ACK_OK));
						break;
					case JOIN_TOPIC : 
						topic = req.data.get(0);
						ServerChatRoom  scr = (ServerChatRoom) rejoindreTopic(topic);
						sendMessage(new Message(MsgType.TOPIC_ADR ,  Integer.toString(scr.getPort())));
					}
					
				} catch (IOException e) {
					if (tries < 3) {
						System.err.println("Malformed message ! soon we kill the session !");
						sendMessage(new Message(Header.MsgType.ACK_ERROR,"Bad message"+ (++tries)));
					} else {
						sendMessage(new Message(Header.MsgType.QUIT_SESSION,"TOO MANY Bad message :"+ (++tries)));
						throw new IOException("Corrupt message");
					}
				}
			}
		} catch (IOException e) {
			System.err.println("Client connection lost !! Error :"+e);			
		}
		System.err.println("Exiting properly ");	
	}


	public Vector<String> listerTopics() {
		return concretGT.listerTopics();
	}


	public void creerTopic(String topic) {
		concretGT.creerTopic(topic);
	}


	public ChatRoom rejoindreTopic(String topic) {
		return concretGT.rejoindreTopic(topic);
	}
	
}
