import Ably from 'ably';
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 SpaceUpdate from './SpaceUpdate.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: 25,
        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,
            },
        };
    }
    async onPresenceUpdate(message) {
        await this.members.processPresenceMessage(message);
        await this.locations.processPresenceMessage(message);
        await this.locks.processPresenceMessage(message);
        this.emit('update', { members: await this.members.getAll() });
    }
    async enter(profileData = null) {
        return new Promise((resolve) => {
            const presence = this.channel.presence;
            presence.subscriptions.once('enter', async () => {
                const presenceMessages = await presence.get();
                presenceMessages.forEach((msg) => this.locks.processPresenceMessage(msg));
                const members = await this.members.getAll();
                resolve(members);
            });
            const update = new SpaceUpdate({ self: null, extras: null });
            this.presenceEnter(update.updateProfileData(profileData));
        });
    }
    async updateProfileData(profileDataOrUpdateFn) {
        const self = await this.members.getSelf();
        if (!isObject(profileDataOrUpdateFn) && !isFunction(profileDataOrUpdateFn)) {
            throw new InvalidArgumentError('Space.updateProfileData(): Invalid arguments: ' + inspect([profileDataOrUpdateFn]));
        }
        let update = new SpaceUpdate({ self, extras: self ? this.locks.getLockExtras(self.connectionId) : null });
        if (!self) {
            const data = update.updateProfileData(isFunction(profileDataOrUpdateFn) ? profileDataOrUpdateFn(null) : profileDataOrUpdateFn);
            await this.presenceEnter(data);
            return;
        }
        else {
            const data = update.updateProfileData(isFunction(profileDataOrUpdateFn) ? profileDataOrUpdateFn(self.profileData) : profileDataOrUpdateFn);
            return this.presenceUpdate(data);
        }
    }
    async leave(profileData = null) {
        const self = await this.members.getSelf();
        if (!self) {
            throw ERR_NOT_ENTERED_SPACE();
        }
        const update = new SpaceUpdate({ self, extras: this.locks.getLockExtras(self.connectionId) });
        let data;
        // Use arguments so it's possible to deliberately nullify profileData on leave
        if (arguments.length > 0) {
            data = update.updateProfileData(profileData);
        }
        else {
            data = update.noop();
        }
        await this.presenceLeave(data);
    }
    async getState() {
        const members = await 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;
