package jp.wda.gpss.samples.chap5;

import java.util.List;

import jp.wda.gpss.GeneralSocklet;
import jp.wda.gpss.SocketProcessor;

/**
 * <FONT SIZE=2><I><B>
 * [ OProject GPSS for FlashMX ] FlashMX用汎用ソケットサーバ Sockletサンプル
 * </B></I></FONT><BR>
 * チュートリアル 第5章　マルチルームチャットSockletを作る<BR>
 * Simple chat Socklet
 *
 * @author	amoi
 */
public class SimpleChatSocklet extends GeneralSocklet {
	public boolean checkConnection(SocketProcessor client) {
		String roomname = client.getInitParam("room");
		
		// このユーザーと同じユーザー名のクライアントを取得
		List cls = getClients("username==" + client.getUserName() + "&a.room==" + roomname);
		if(cls.size() > 0){
			client.send("-Login failure");
			return false;
		}
		
		client.send("+Welcome");
		sendToClients("<message command=\"1\" user=\"" + client.getUserName() + "\" />", "a.room==" + roomname);
		client.setAttribute("room", roomname);
		return true;
	}
	
	public void preRemoveClient(SocketProcessor client) {
		String roomname = (String)client.getAttribute("room");
		sendToClients("<message command=\"3\" user=\"" + client.getUserName() + "\"/>", "a.room==" + roomname);
		return;
	}
	
	public boolean doCommand(SocketProcessor client, String command) {
		if(command.length() <= 7)   { return true; }
		if(command.charAt(0) != '@'){ return true; }
		
		String roomname = (String)client.getAttribute("room");
		String message  = command.substring(7);
		
		sendToClients("<message command=\"2\" user=\"" + client.getUserName() + "\">" + message + "</message>", "a.room==" + roomname);
		return true;
	}

}
