// retoor <retoor@molodetz.nl>

export class EditorLauncher {
    constructor() {
        document.addEventListener("click", (event) => this.onClick(event));
    }

    onClick(event) {
        const trigger = event.target.closest("[data-editor-open]");
        if (!trigger) return;
        const mode = trigger.dataset.editorMode || "tab";
        if (mode === "tab") return;
        const opened = window.open(
            trigger.href,
            trigger.dataset.editorName || "devplace-editor",
            this.features(mode, trigger),
        );
        if (!opened) return;
        event.preventDefault();
        opened.focus();
    }

    features(mode, trigger) {
        const size = this.size(mode, trigger);
        const left = Math.max(0, Math.round((window.screen.availWidth - size.width) / 2));
        const top = Math.max(0, Math.round((window.screen.availHeight - size.height) / 2));
        return [
            `width=${size.width}`,
            `height=${size.height}`,
            `left=${left}`,
            `top=${top}`,
            "noopener",
            "resizable=yes",
            "scrollbars=yes",
        ].join(",");
    }

    size(mode, trigger) {
        if (mode === "fullscreen") {
            return {
                width: window.screen.availWidth,
                height: window.screen.availHeight,
            };
        }
        return {
            width: this.clamp(trigger.dataset.editorWidth, 640, window.screen.availWidth),
            height: this.clamp(trigger.dataset.editorHeight, 480, window.screen.availHeight),
        };
    }

    clamp(raw, minimum, maximum) {
        const value = parseInt(raw, 10);
        if (!Number.isFinite(value)) return maximum;
        return Math.max(minimum, Math.min(maximum, value));
    }
}

export default EditorLauncher;
