"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 ably_1 = __importDefault(require("ably"));
const nanoid_1 = require("nanoid");
const EventEmitter_js_1 = __importStar(require("./utilities/EventEmitter.js"));
const Locations_js_1 = __importDefault(require("./Locations.js"));
const Cursors_js_1 = __importDefault(require("./Cursors.js"));
const Members_js_1 = __importDefault(require("./Members.js"));
const Locks_js_1 = __importDefault(require("./Locks.js"));
const Errors_js_1 = require("./Errors.js");
const is_js_1 = require("./utilities/is.js");
// Replace by ::$space when that channel tag will be available
const SPACE_CHANNEL_TAG = '-space';
const SPACE_OPTIONS_DEFAULTS = {
    offlineTimeout: 120000,
    cursors: {
        outboundBatchInterval: 100,
        paginationLimit: 5,
    },
};
class Space extends EventEmitter_js_1.default {
    constructor(name, client, options) {
        super();
        this.client = client;
        this.presenceUpdate = (data, extras) => {
            if (!extras) {
                return this.channel.presence.update(data);
            }
            return this.channel.presence.update(ably_1.default.Realtime.PresenceMessage.fromValues({ data, extras }));
        };
        this.presenceEnter = (data, extras) => {
            if (!extras) {
                return this.channel.presence.enter(data);
            }
            return this.channel.presence.enter(ably_1.default.Realtime.PresenceMessage.fromValues({ data, extras }));
        };
        this.presenceLeave = (data, extras) => {
            if (!extras) {
                return this.channel.presence.leave(data);
            }
            return this.channel.presence.leave(ably_1.default.Realtime.PresenceMessage.fromValues({ data, extras }));
        };
        this.options = this.setOptions(options);
        this.connectionId = this.client.connection.id;
        this.name = name;
        this.channelName = `${name}${SPACE_CHANNEL_TAG}`;
        this.channel = this.client.channels.get(this.channelName);
        this.onPresenceUpdate = this.onPresenceUpdate.bind(this);
        this.channel.presence.subscribe(this.onPresenceUpdate);
        this.locations = new Locations_js_1.default(this, this.presenceUpdate);
        this.cursors = new Cursors_js_1.default(this);
        this.members = new Members_js_1.default(this);
        this.locks = new Locks_js_1.default(this, this.presenceUpdate);
    }
    setOptions(options) {
        var _a, _b, _c, _d, _e;
        const { offlineTimeout, cursors: { outboundBatchInterval, paginationLimit }, } = SPACE_OPTIONS_DEFAULTS;
        return {
            offlineTimeout: (_a = options === null || options === void 0 ? void 0 : options.offlineTimeout) !== null && _a !== void 0 ? _a : offlineTimeout,
            cursors: {
                outboundBatchInterval: (_c = (_b = options === null || options === void 0 ? void 0 : options.cursors) === null || _b === void 0 ? void 0 : _b.outboundBatchInterval) !== null && _c !== void 0 ? _c : outboundBatchInterval,
                paginationLimit: (_e = (_d = options === null || options === void 0 ? void 0 : options.cursors) === null || _d === void 0 ? void 0 : _d.paginationLimit) !== null && _e !== void 0 ? _e : paginationLimit,
            },
        };
    }
    onPresenceUpdate(message) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.members.processPresenceMessage(message);
            yield this.locations.processPresenceMessage(message);
            yield this.locks.processPresenceMessage(message);
            this.emit('update', { members: yield this.members.getAll() });
        });
    }
    enter(profileData = null) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve) => {
                const presence = this.channel.presence;
                presence.subscriptions.once('enter', () => __awaiter(this, void 0, void 0, function* () {
                    const presenceMessages = yield presence.get();
                    presenceMessages.forEach((msg) => this.locks.processPresenceMessage(msg));
                    const members = yield this.members.getAll();
                    resolve(members);
                }));
                this.presenceEnter({
                    profileUpdate: {
                        id: (0, nanoid_1.nanoid)(),
                        current: profileData,
                    },
                    locationUpdate: {
                        id: null,
                        current: null,
                        previous: null,
                    },
                });
            });
        });
    }
    updateProfileData(profileDataOrUpdateFn) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.members.getSelf();
            if (!(0, is_js_1.isObject)(profileDataOrUpdateFn) && !(0, is_js_1.isFunction)(profileDataOrUpdateFn)) {
                throw new EventEmitter_js_1.InvalidArgumentError('Space.updateProfileData(): Invalid arguments: ' + (0, EventEmitter_js_1.inspect)([profileDataOrUpdateFn]));
            }
            const update = {
                profileUpdate: {
                    id: (0, nanoid_1.nanoid)(),
                    current: (0, is_js_1.isFunction)(profileDataOrUpdateFn) ? profileDataOrUpdateFn(null) : profileDataOrUpdateFn,
                },
                locationUpdate: {
                    id: null,
                    current: (_a = self === null || self === void 0 ? void 0 : self.location) !== null && _a !== void 0 ? _a : null,
                    previous: null,
                },
            };
            if (!self) {
                yield this.presenceEnter(update);
                return;
            }
            const extras = this.locks.getLockExtras(self.connectionId);
            return this.presenceUpdate(update, extras);
        });
    }
    leave(profileData = null) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.members.getSelf();
            if (!self) {
                throw (0, Errors_js_1.ERR_NOT_ENTERED_SPACE)();
            }
            const update = {
                profileUpdate: {
                    id: profileData ? (0, nanoid_1.nanoid)() : null,
                    current: profileData !== null && profileData !== void 0 ? profileData : null,
                },
                locationUpdate: {
                    id: null,
                    current: (_a = self === null || self === void 0 ? void 0 : self.location) !== null && _a !== void 0 ? _a : null,
                    previous: null,
                },
            };
            yield this.presenceLeave(update);
        });
    }
    getState() {
        return __awaiter(this, void 0, void 0, function* () {
            const members = yield this.members.getAll();
            return { members };
        });
    }
    subscribe(listenerOrEvents, listener) {
        try {
            super.on(listenerOrEvents, listener);
        }
        catch (e) {
            if (e instanceof EventEmitter_js_1.InvalidArgumentError) {
                throw new EventEmitter_js_1.InvalidArgumentError('Space.subscribe(): Invalid arguments: ' + (0, EventEmitter_js_1.inspect)([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
    }
    unsubscribe(listenerOrEvents, listener) {
        try {
            super.off(listenerOrEvents, listener);
        }
        catch (e) {
            if (e instanceof EventEmitter_js_1.InvalidArgumentError) {
                throw new EventEmitter_js_1.InvalidArgumentError('Space.unsubscribe(): Invalid arguments: ' + (0, EventEmitter_js_1.inspect)([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
    }
}
exports.default = Space;
//# sourceMappingURL=Space.js.map