package org.mynonglam.dao;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.mynonglam.entitys.Client;
import org.mynonglam.entitys.Message;
import org.mynonglam.server.Chat;

public class ChatMessageMod extends MessageInbound {
	private String username;
	private Client client;
	private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("hh:mm");
	private static SimpleDateFormat SAVED_DATE_FORMAT = new SimpleDateFormat("dd/MM/yy - hh:mm");
	private Emoticon emo;
	private MessageMod mesMod;
	
	public ChatMessageMod(String username){
		this.username = username;
		this.emo = new Emoticon();
		mesMod = new MessageMod();
	}
	
	@Override
	protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onTextMessage(CharBuffer cb) throws IOException {
		String data = cb.toString();
		StringTokenizer tokens = new StringTokenizer(data, "\0");
		
		String com = tokens.nextToken();

		if (com.equals("chat")){
			String to = tokens.nextToken();
			String content = tokens.nextToken();
			content = emo.replaceEmo(content);
			String active = "0";
			if (checkOnline(to)) active = "1";
			mesMod.createMessage(new Message("", this.username, to, content, SAVED_DATE_FORMAT.format(new Date()), active));
			sendPrivate("pri\0" + this.username + "\0" + to + "\0" + content.trim() + "\0" + DATE_FORMAT.format(new Date()), to);
			sendPrivate("pri\0" + this.username + "\0" + to + "\0" + content.trim() + "\0" + DATE_FORMAT.format(new Date()), this.username);
		}
	}

	@Override
	protected void onClose(int status) {
		System.out.println("Remove: " + this.getWsOutbound().toString());
		Chat.clientList.remove(this.client);
		sendBroadcast("pub\0offline\0" + username);
	}
	
	@Override
	protected void onOpen(WsOutbound out) {
		System.out.println("add: " + out.toString());
		this.client = new Client(this.username, out);
		Chat.clientList.add(client);
		
		sendBroadcast("pub\0online\0" + username);
		sendOnlineList();
	}
	
	private static void  sendBroadcast(String content){
        for (Client netOut : Chat.clientList) {
    		try {
				netOut.getNetOut().writeTextMessage(CharBuffer.wrap(content));
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
	
	public void sendPrivate(String content, String receiver){
		try {
	        for (Client netOut : Chat.clientList) {
	        	if (netOut.getUsername().equals(receiver)){	
    				netOut.getNetOut().writeTextMessage(CharBuffer.wrap(content));
    			}
			}
        }catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendOnlineList(){
		String data = "";
		for (int i = 0; i < Chat.clientList.size() - 1; i++) {
			data += Chat.clientList.get(i).getUsername() + ",";
		}
		data += Chat.clientList.get((Chat.clientList.size() - 1)).getUsername();
		try {
			this.client.getNetOut().writeTextMessage(CharBuffer.wrap("online\0list\0" + data));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean checkOnline(String user){
		boolean result = false;
        for (Client netOut : Chat.clientList) {
        	if (netOut.getUsername().equals(user)){	
        		result = true;
			}
		}
		return result;
	}
}
