package org.mynonglam.server;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mynonglam.dao.Notification;
import org.mynonglam.entitys.Client;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

/**
 * Servlet implementation class Notification
 */
public class Notificate extends WebSocketServlet {
	
	private static final long serialVersionUID = 1L;
	
	public static ArrayList<Client> clientListNotfi = new ArrayList<Client>();
	
	HttpSession session;
	
	public Notificate(){}
	 
    @Override
    protected StreamInbound createWebSocketInbound(String string, HttpServletRequest request) {
    	session = request.getSession();
    	return new Notification((String) session.getAttribute("accountinfo"));
	}
    
	public static void  sendBroadcast(String content){
        for (Client netOut : clientListNotfi) {
    		try {
				netOut.getNetOut().writeTextMessage(CharBuffer.wrap(content));
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
	
	public static void sendPrivate(String receiver, String content){
		try {
	        for (Client netOut : clientListNotfi) {
	        	if (netOut.getUsername().equals(receiver)){	
    				netOut.getNetOut().writeTextMessage(CharBuffer.wrap(content));
    			}
			}
        }catch (IOException e) {
			e.printStackTrace();
		}
	}
}
