package cz.vavru.test.dwr.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServlet;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;

import cz.vavru.test.dwr.domain.Message;
import cz.vavru.test.dwr.domain.User;
import cz.vavru.test.dwr.service.ChatServiceImpl;

/**
 * 
 * @author vlastimil@vavru.cz (http://vavru.cz)
 *
 */
public class DwrWebContextUtil {
	WebContext webCtx;
	String currentPage;

	public DwrWebContextUtil(WebContext webCtx) {
		this.webCtx = webCtx;
		this.currentPage = webCtx.getCurrentPage();
	}

	@SuppressWarnings("unchecked")
	public Collection<ScriptSession> getAllCurrentPageScriptSessions() {
		return (Collection<ScriptSession>) webCtx.getScriptSessionsByPage(currentPage);
	}

	@SuppressWarnings("unchecked")
	public Collection<ScriptSession> getScriptSessionsToNotifyAboutNewMessage(Message message) {
		Collection<ScriptSession> pageScriptSessions = (Collection<ScriptSession>) webCtx
				.getScriptSessionsByPage(currentPage);

		Collection<ScriptSession> scriptSessions = new ArrayList<ScriptSession>();

		if (message.getRecipient() != null) {
			for (Iterator<ScriptSession> it = pageScriptSessions.iterator(); it.hasNext();) {
				ScriptSession scriptSession = it.next();
				User user = (User) scriptSession.getAttribute(ChatServiceImpl.SCRIPT_CHAT_USER_SES_ATTR);
				if(user == null) continue;
				
				if (message.getSender().getUserId() == user.getUserId()
						|| message.getRecipient().getUserId() == user.getUserId()) {
					scriptSessions.add(scriptSession);
				}
			}
		} else {
			scriptSessions = pageScriptSessions;
		}

		return scriptSessions;
	}

}
