import {idFromSynchronized, synchronizedFromId} from './registry'; import {SynchronizedCreatePacket} from './synchronized-create.packet'; import {SynchronizedDestroyPacket} from './synchronized-destroy.packet'; import {SynchronizedUpdatePacket} from './synchronized-update.packet'; export class ClientSynchronizer { constructor() { this._synchronized = {}; } acceptPackets(packets) { for (let i = 0; i < packets.length; i++) { const packet = packets[i]; if ((packet instanceof SynchronizedCreatePacket)) { const json = packet.data.spec; const {id, type} = packet.data.synchronized; const Synchronized = synchronizedFromId(type); if (!(type in this._synchronized)) { this._synchronized[type] = {}; } if (this._synchronized[type][id]) { this._synchronized[type][id].fromJSON(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 = idFromSynchronized(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; } }