jingrow.provide("jingrow.model.user_settings");

$.extend(jingrow.model.user_settings, {
	get: function (pagetype) {
		return jingrow
			.call("jingrow.model.utils.user_settings.get", { pagetype })
			.then((r) => JSON.parse(r.message || "{}"));
	},
	save: function (pagetype, key, value) {
		if (jingrow.session.user === "Guest") return Promise.resolve();

		const old_user_settings = jingrow.model.user_settings[pagetype] || {};
		const new_user_settings = $.extend(true, {}, old_user_settings); // deep copy

		if ($.isPlainObject(value)) {
			new_user_settings[key] = new_user_settings[key] || {};
			$.extend(new_user_settings[key], value);
		} else {
			new_user_settings[key] = value;
		}

		const a = JSON.stringify(old_user_settings);
		const b = JSON.stringify(new_user_settings);
		if (a !== b) {
			// update if changed
			return this.update(pagetype, new_user_settings);
		}
		return Promise.resolve(new_user_settings);
	},
	remove: function (pagetype, key) {
		var user_settings = jingrow.model.user_settings[pagetype] || {};
		delete user_settings[key];

		return this.update(pagetype, user_settings);
	},
	update: function (pagetype, user_settings) {
		if (jingrow.session.user === "Guest") return Promise.resolve();
		return jingrow.call({
			method: "jingrow.model.utils.user_settings.save",
			args: {
				pagetype: pagetype,
				user_settings: user_settings,
			},
			callback: function (r) {
				jingrow.model.user_settings[pagetype] = r.message;
			},
		});
	},
});

jingrow.get_user_settings = function (pagetype, key) {
	var settings = jingrow.model.user_settings[pagetype] || {};
	if (key) {
		settings = settings[key] || {};
	}
	return settings;
};
