import { Communicator } from "../../communication";
import "./popup.scss";

const con = new Communicator();

class Toggle extends HTMLButtonElement {
	isON: boolean = false;
	textContent: string = "OFF";

	public set on(v: boolean) {
		if (this.isON == v) {
			return;
		}
		this.isON = v;
		this.render();
	}
	public get on(): boolean {
		return this.isON;
	}

	public render() {
		this.textContent = this.on ? "ON" : "OFF";
	}

	constructor() {
		super();
		this.addEventListener("click", () => {
			this.on = !this.on;

			const toggleEvent = new CustomEvent("toggled", {
				detail: this.on,
			});
			this.dispatchEvent(toggleEvent);
		});
	}
}
customElements.define("lingo-toggle", Toggle, {
	extends: "button",
});

const toggle = <Toggle>document.querySelector("button[is=lingo-toggle]");
toggle.addEventListener("toggled", ((e: CustomEvent) => {
	Communicator.setEnabled(e.detail);
}) as EventListener); //Hate to do this but ts forced me

con.setEnabledCallback = (v) => (toggle.on = v);
Communicator.getEnabled().then((v) => (toggle.on = v));