// retoor <retoor@molodetz.nl>
import { Http } from "./Http.js";
class NotificationPrefs {
constructor() {
this.root = document.querySelector("[data-notif-prefs]");
if (!this.root) return;
this.username = this.root.dataset.username;
this.root
.querySelectorAll("[data-notif-toggle]")
.forEach((input) => this.bind(input));
const reset = this.root.querySelector("[data-notif-reset]");
if (reset) reset.addEventListener("click", () => this.reset(reset));
}
bind(input) {
input.addEventListener("change", async () => {
const desired = input.checked;
input.disabled = true;
try {
await Http.send(`/profile/${this.username}/notifications`, {
notification_type: input.dataset.type,
channel: input.dataset.channel,
value: desired ? "true" : "false",
});
this.flash(desired ? "Saved" : "Disabled", "success");
} catch (error) {
input.checked = !desired;
this.flash("Could not save notification setting", "error");
} finally {
input.disabled = false;
}
});
}
async reset(button) {
button.disabled = true;
try {
await Http.send(`/profile/${this.username}/notifications/reset`, {});
window.location.reload();
} catch (error) {
button.disabled = false;
this.flash("Could not reset notifications", "error");
}
}
flash(message, type) {
if (window.app && window.app.toast) {
window.app.toast.show(message, { type });
}
}
}
window.NotificationPrefs = NotificationPrefs;
export { NotificationPrefs };