import {fromId} from './s13n.scwp'; import {idFrom} from './registrar'; import SynchronizedCreatePacket from './synchronized-create.packet'; import SynchronizedDestroyPacket from './synchronized-destroy.packet'; import SynchronizedUpdatePacket from './synchronized-update.packet'; export class ClientSynchronizer { constructor() { this._synchronized = {}; } acceptPacket(packet) { if ((packet instanceof SynchronizedCreatePacket)) { const json = packet.data.spec; const {id, type} = packet.data.synchronized; const {default: Synchronized} = fromId(type); if (!(type in this._synchronized)) { this._synchronized[type] = {}; } if (this._synchronized[type][id]) { this._synchronized[type][id].fromNetwork(json); } else { this._synchronized[type][id] = new Synchronized(json); } } else if ((packet instanceof SynchronizedUpdatePacket)) { const { synchronized: {id, type}, } = packet.data; this._synchronized[type][id].acceptPacket(packet); } else if ((packet instanceof SynchronizedDestroyPacket)) { const { synchronized: {id, type}, } = packet.data; this._synchronized[type][id].destroy(); this._synchronized[type][id] = null; } } addSynchronized(synchronized) { const type = idFrom(synchronized.constructor); if (!(type in this._synchronized)) { this._synchronized[type] = new Map(); } const synchronizationId = synchronized.synchronizationId(); if (this._synchronized[type].has(synchronizationId)) { return; } this._synchronized[type][synchronizationId] = synchronized; } synchronized(type, id) { if (!this._synchronized[type]) { return; } return this._synchronized[type][id]; } }