"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const CursorBatching_js_1 = __importDefault(require("./CursorBatching.js"));
const CursorDispensing_js_1 = __importDefault(require("./CursorDispensing.js"));
const EventEmitter_js_1 = __importStar(require("./utilities/EventEmitter.js"));
const CursorHistory_js_1 = __importDefault(require("./CursorHistory.js"));
const CursorConstants_js_1 = require("./CursorConstants.js");
const Errors_js_1 = require("./Errors.js");
const CURSORS_CHANNEL_TAG = '::$cursors';
class Cursors extends EventEmitter_js_1.default {
    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_js_1.default();
        this.cursorBatching = new CursorBatching_js_1.default(this.options.outboundBatchInterval);
        const emitCursorUpdate = (update) => this.emit('update', update);
        this.cursorDispensing = new CursorDispensing_js_1.default(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 (0, Errors_js_1.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 * 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 EventEmitter_js_1.InvalidArgumentError) {
                throw new EventEmitter_js_1.InvalidArgumentError('Cursors.subscribe(): Invalid arguments: ' + (0, EventEmitter_js_1.inspect)([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
        if (this.isUnsubscribed()) {
            const channel = this.getChannel();
            channel.subscribe(CursorConstants_js_1.CURSOR_UPDATE, (message) => {
                this.cursorDispensing.processBatch(message);
            });
        }
    }
    unsubscribe(listenerOrEvents, listener) {
        try {
            super.off(listenerOrEvents, listener);
        }
        catch (e) {
            if (e instanceof EventEmitter_js_1.InvalidArgumentError) {
                throw new EventEmitter_js_1.InvalidArgumentError('Cursors.unsubscribe(): Invalid arguments: ' + (0, EventEmitter_js_1.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);
        });
    }
}
exports.default = Cursors;
//# sourceMappingURL=Cursors.js.map