var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import CursorBatching from './CursorBatching.js';
import CursorDispensing from './CursorDispensing.js';
import EventEmitter, { InvalidArgumentError, inspect, } from './utilities/EventEmitter.js';
import CursorHistory from './CursorHistory.js';
import { CURSOR_UPDATE } from './CursorConstants.js';
import { ERR_NOT_ENTERED_SPACE } from './Errors.js';
const CURSORS_CHANNEL_TAG = '::$cursors';
export default class Cursors extends EventEmitter {
    constructor(space) {
        super();
        this.space = space;
        this.emitterHasListeners = (emitter) => {
            const flattenEvents = (obj) => Object.entries(obj)
                .map((_, v) => v)
                .flat();
            return (emitter.any.length > 0 ||
                emitter.anyOnce.length > 0 ||
                flattenEvents(emitter.events).length > 0 ||
                flattenEvents(emitter.eventsOnce).length > 0);
        };
        this.options = this.space.options.cursors;
        this.channelName = `${this.space.name}${CURSORS_CHANNEL_TAG}`;
        this.cursorHistory = new CursorHistory();
        this.cursorBatching = new CursorBatching(this.options.outboundBatchInterval);
        const emitCursorUpdate = (update) => this.emit('update', update);
        this.cursorDispensing = new CursorDispensing(emitCursorUpdate);
    }
    /**
     * Schedules a cursor update event to be sent that will cause the following events to fire
     *
     * @param {CursorUpdate} cursor
     * @return {void}
     */
    set(cursor) {
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.space.members.getSelf();
            if (!self) {
                throw ERR_NOT_ENTERED_SPACE();
            }
            const channel = this.getChannel();
            this.cursorBatching.pushCursorPosition(channel, cursor);
        });
    }
    getChannel() {
        var _a;
        return (_a = this.channel) !== null && _a !== void 0 ? _a : (this.channel = this.initializeCursorsChannel());
    }
    initializeCursorsChannel() {
        const channel = this.space.client.channels.get(this.channelName);
        channel.presence.subscribe(this.onPresenceUpdate.bind(this));
        channel.presence.enter();
        return channel;
    }
    onPresenceUpdate() {
        return __awaiter(this, void 0, void 0, function* () {
            const channel = this.getChannel();
            const cursorsMembers = yield channel.presence.get();
            this.cursorBatching.setShouldSend(cursorsMembers.length > 1);
            this.cursorBatching.setBatchTime((cursorsMembers.length - 1) * this.options.outboundBatchInterval);
        });
    }
    isUnsubscribed() {
        const channel = this.getChannel();
        const subscriptions = channel.subscriptions;
        return !this.emitterHasListeners(subscriptions);
    }
    subscribe(listenerOrEvents, listener) {
        try {
            super.on(listenerOrEvents, listener);
        }
        catch (e) {
            if (e instanceof InvalidArgumentError) {
                throw new InvalidArgumentError('Cursors.subscribe(): Invalid arguments: ' + inspect([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
        if (this.isUnsubscribed()) {
            const channel = this.getChannel();
            channel.subscribe(CURSOR_UPDATE, (message) => {
                this.cursorDispensing.processBatch(message);
            });
        }
    }
    unsubscribe(listenerOrEvents, listener) {
        try {
            super.off(listenerOrEvents, listener);
        }
        catch (e) {
            if (e instanceof InvalidArgumentError) {
                throw new InvalidArgumentError('Cursors.unsubscribe(): Invalid arguments: ' + inspect([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
        const hasListeners = this.emitterHasListeners(this);
        if (!hasListeners) {
            const channel = this.getChannel();
            channel.unsubscribe();
        }
    }
    getSelf() {
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.space.members.getSelf();
            if (!self)
                return null;
            const allCursors = yield this.getAll();
            return allCursors[self.connectionId];
        });
    }
    getOthers() {
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.space.members.getSelf();
            if (!self)
                return {};
            const allCursors = yield this.getAll();
            const allCursorsFiltered = allCursors;
            delete allCursorsFiltered[self.connectionId];
            return allCursorsFiltered;
        });
    }
    getAll() {
        return __awaiter(this, void 0, void 0, function* () {
            const channel = this.getChannel();
            return yield this.cursorHistory.getLastCursorUpdate(channel, this.options.paginationLimit);
        });
    }
}
//# sourceMappingURL=Cursors.js.map