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 Ably from 'ably';
import { nanoid } from 'nanoid';
import EventEmitter, { InvalidArgumentError, inspect, } from './utilities/EventEmitter.js';
import Locations from './Locations.js';
import Cursors from './Cursors.js';
import Members from './Members.js';
import Locks from './Locks.js';
import { ERR_NOT_ENTERED_SPACE } from './Errors.js';
import { isFunction, isObject } from './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 {
    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.Realtime.PresenceMessage.fromValues({ data, extras }));
        };
        this.presenceEnter = (data, extras) => {
            if (!extras) {
                return this.channel.presence.enter(data);
            }
            return this.channel.presence.enter(Ably.Realtime.PresenceMessage.fromValues({ data, extras }));
        };
        this.presenceLeave = (data, extras) => {
            if (!extras) {
                return this.channel.presence.leave(data);
            }
            return this.channel.presence.leave(Ably.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(this, this.presenceUpdate);
        this.cursors = new Cursors(this);
        this.members = new Members(this);
        this.locks = new Locks(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: 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 (!isObject(profileDataOrUpdateFn) && !isFunction(profileDataOrUpdateFn)) {
                throw new InvalidArgumentError('Space.updateProfileData(): Invalid arguments: ' + inspect([profileDataOrUpdateFn]));
            }
            const update = {
                profileUpdate: {
                    id: nanoid(),
                    current: 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 ERR_NOT_ENTERED_SPACE();
            }
            const update = {
                profileUpdate: {
                    id: profileData ? 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 InvalidArgumentError) {
                throw new InvalidArgumentError('Space.subscribe(): Invalid arguments: ' + inspect([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
    }
    unsubscribe(listenerOrEvents, listener) {
        try {
            super.off(listenerOrEvents, listener);
        }
        catch (e) {
            if (e instanceof InvalidArgumentError) {
                throw new InvalidArgumentError('Space.unsubscribe(): Invalid arguments: ' + inspect([listenerOrEvents, listener]));
            }
            else {
                throw e;
            }
        }
    }
}
export default Space;
//# sourceMappingURL=Space.js.map