/* CounterWithPassword.bsh - an agent in BeanShell.
*
* Copyright (C) 2002 Jacques Ferber
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

import madkit.utils.common.*;

String myCommunity="tutorial";
String myGroup="demo.count.passwd";
String myRole="counter";

String passwd="madkit";

boolean alive = true; 

void activate(){
	self.println("Hello I'm an agent !");
	// create a distributed group
	int g = self.createGroup(true, myCommunity, myGroup, null, new SimplePasswdFilter(passwd));
	if (g == 1)
		self.println("I create the group "+myGroup+" in community "+myCommunity);
	else if (g == -1)
		self.println("The group has already been created");
	else
		self.println("Cannot create the group");
		
	int r = self.requestRole(myCommunity, myGroup, myRole,passwd);
	if (r == 1)
		self.println("I play "+ myRole + " in " + myGroup + " of " + myCommunity);
	else if (r == -1)
		self.println("I cannot enter the group: access denied");
	else if (r == -2)
		self.println("I already play the role "+myRole+" in " + myGroup + " of " + myCommunity);
	else if (r == -3)
		self.println("The group "+myGroup+" does not exist int the community "+myCommunity);
	else if (r == -4)
		self.println("The community "+myCommunity+" does not exist");
}

void live()
{
	self.println("I am ready to count");
	int n = 0;
    	boolean counting = false;
    	while (alive) {
        	Message m = self.nextMessage();
		if (m == null){
            		if (counting){
                		self.println("counting: "+n);
                		n = n+1;
			}
			self.println("waiting..");
			self.pause(1000);
		} else if (m.getString().equalsIgnoreCase("start")) {
			counting = true;
		} else if (m.getString().equalsIgnoreCase("stop")) {
			counting = false;
		}
	} 
}

