dao-governance-framework/forum-network/public/classes/actor.js

72 lines
1.7 KiB
JavaScript

export class Actor {
constructor(name, scene) {
this.name = name;
this.scene = scene;
this.callbacks = new Map();
this.status = this.scene.addDisplayValue(`${this.name} status`);
this.status.set('New');
this.scene.log(`participant ${this.name}`);
this.values = new Map();
this.active = 0;
this.scene.registerActor(this);
}
activate() {
this.active += 1;
this.scene.log(`activate ${this.name}`);
}
deactivate() {
if (!this.active) {
throw new Error(`${this.name} is not active, can not deactivate`);
}
this.active -= 1;
this.scene.log(`deactivate ${this.name}`);
}
send(dest, action, detail) {
action.log(this, dest, detail ? JSON.stringify(detail) : '');
dest.recv(this, action, detail);
return this;
}
recv(src, action, detail) {
const cb = this.callbacks.get(action.name);
if (!cb) {
throw new Error(
`[${this.scene.name} actor ${this.name} does not have a callback registered for ${action.name}`,
);
}
cb(src, detail);
return this;
}
on(action, cb) {
this.callbacks.set(action.name, cb);
return this;
}
setStatus(status) {
this.status.set(status);
return this;
}
addValue(label) {
this.values.set(label, this.scene.addDisplayValue(`${this.name} ${label}`));
return this;
}
setValue(label, value) {
let displayValue = this.values.get(label);
if (!displayValue) {
displayValue = this.scene.addDisplayValue(`${this.name} ${label}`);
this.values.set(label, displayValue);
}
if (value !== displayValue.get()) {
this.scene.log(`note over ${this.name} : ${label} = ${value}`);
}
displayValue.set(value);
return this;
}
}