il.ac.bgu.cs.bp.bpjs.model.BEvent Maven / Gradle / Ivy
package il.ac.bgu.cs.bp.bpjs.model;
import il.ac.bgu.cs.bp.bpjs.internal.ScriptableUtils;
import il.ac.bgu.cs.bp.bpjs.model.eventsets.EventSet;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.mozilla.javascript.Scriptable;
/**
* A base class for events. Each event has a name and optional data, which is a
* JavaScript object.
*
* For two events to be equal, their names and data have to match.
*
* Each event implicitly defines a singleton {@link EventSet}, which contains
* only itself.
*/
@SuppressWarnings("serial")
public class BEvent implements Comparable, EventSet, java.io.Serializable {
private static final ConcurrentHashMap NAME_INDICES =new ConcurrentHashMap<>();
/**
* Name of the event. Public access, so that the Javascript code feels
* natural.
*/
public final String name;
/**
* Extra data for the event. Public access, so that the Javascript code
* feels natural.
*/
public final Object maybeData;
public static BEvent named(String aName) {
return new BEvent(aName);
}
public BEvent(String aName) {
this(aName, null);
}
public BEvent(String aName, Object someData) {
name = aName;
maybeData = someData;
}
public BEvent() {
String className[] = getClass().getCanonicalName().split("\\.");
String baseName = className[className.length-1];
int index = NAME_INDICES.computeIfAbsent(baseName, n->new AtomicInteger()).incrementAndGet();
name = baseName+"-"+index;
maybeData = null;
}
@Override
public String toString() {
return "[BEvent name:" + name + (getDataField().map(v -> " data:" + dataToString(v)).orElse("")) + "]";
}
public String getName() {
return name;
}
/**
* @return The data field of the event.
*/
public Optional