/* This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

export function addViewers(): [() => void, () => void] {
    const body = document.querySelector("body");
    if (!body) {
        throw "incorporeal?";
    }
    let activeViewer: HTMLDivElement | undefined;
    let viewersActive = true;

    document.querySelectorAll("main img").forEach(img => {
        const activate = () => {
            const viewer = document.createElement("div");
            viewer.classList.add("viewer");
            const viewerImg = document.createElement("img");
            const alt = img.getAttribute("alt");
            if (alt) {
                viewerImg.setAttribute("alt", alt);
            }
            viewerImg.setAttribute("src", img.getAttribute("src")!);
            if (img.classList.contains("has-transparency")) {
                viewerImg.classList.add("has-transparency");
            }
            if (img.classList.contains("ly-img")) {
                viewerImg.classList.add("ly-img");
                viewerImg.classList.remove("has-transparency");
            }
            viewer.append(viewerImg);

            if (activeViewer) {
                activeViewer.remove();
            }
            activeViewer = viewer;
            body.append(viewer);
        };

        img.addEventListener("click", ev => {
            if (!viewersActive) {
                return;
            }

            activate();
            ev.stopPropagation();
            ev.preventDefault();
        });
        img.addEventListener("keydown", ev => {
            if (
                !viewersActive ||
                !(ev instanceof KeyboardEvent) ||
                ev.key !== "Enter"
            ) {
                return;
            }
            activate();
            ev.stopPropagation();
            ev.preventDefault();
        });
    });

    const deactivate = () => {
        if (activeViewer) {
            activeViewer.remove();
        }
        activeViewer = undefined;
    };
    document.addEventListener("click", deactivate);
    document.addEventListener("keydown", ev => {
        if (ev instanceof KeyboardEvent && ev.key !== "Tab") {
            deactivate();
        }
    });

    const disableViewers = () => {
        deactivate();
        viewersActive = false;
    };
    const enableViewers = () => (viewersActive = true);

    return [disableViewers, enableViewers];
}
