jingrow.ui.form.FormViewers = class FormViewers {
	constructor({ frm, parent }) {
		this.frm = frm;
		this.parent = parent;
		this.parent.tooltip({ title: __("Currently Viewing") });

		this._past_users = {};
		this._active_users = {};
		this.setup_events();
	}

	get past_users() {
		return this._past_users[this.frm?.pg?.name] || [];
	}

	set past_users(users) {
		const pagename = this.frm?.pg?.name;
		if (!pagename) return;

		this._past_users[pagename] = users;
	}

	get active_users() {
		return this._active_users[this.frm?.pg?.name] || [];
	}

	set active_users(users) {
		const pagename = this.frm?.pg?.name;
		if (!pagename) return;

		this._active_users[pagename] = users;
	}

	refresh() {
		if (!this.active_users.length) {
			this.parent.empty();
			return;
		}
		let avatar_group = jingrow.avatar_group(this.active_users, 5, {
			align: "left",
			overlap: true,
		});
		this.parent.empty().append(avatar_group);
	}

	setup_events() {
		let me = this;
		jingrow.realtime.off("pg_viewers");
		jingrow.realtime.on("pg_viewers", function (data) {
			me.update_users(data);
		});
	}

	async update_users({ pagetype, pagename, users = [] }) {
		users = users.filter((u) => u != jingrow.session.user);

		const added_users = users.filter((user) => !this.past_users.includes(user));
		const removed_users = this.past_users.filter((user) => !users.includes(user));
		const changed_users = [...added_users, ...removed_users];

		if (changed_users.length === 0) return;

		await this.fetch_user_info(users);

		this.active_users = users;
		this.past_users = users;

		if (this.frm?.pg?.pagetype === pagetype && this.frm?.pg?.name == pagename) {
			this.refresh();
		}
	}

	async fetch_user_info(users) {
		let unknown_users = [];
		for (let user of users) {
			if (!jingrow.boot.user_info[user]) unknown_users.push(user);
		}
		if (!unknown_users.length) return;

		const data = await jingrow.xcall("jingrow.desk.form.load.get_user_info_for_viewers", {
			users: unknown_users,
		});
		Object.assign(jingrow.boot.user_info, data);
	}
};
