import Panzoom from '@panzoom/panzoom';
import { PanzoomObject } from "@panzoom/panzoom/dist/src/types";
import { config } from "./config";

export function addPanzoom(inSelector: string, inBtnZoomIn: string | undefined = undefined, inBtnZoomOut: string | undefined = undefined, inBtnResetZoom: string | undefined = undefined): PanzoomObject | undefined {
    const container: HTMLElement = jQuery(inSelector).get(0);

    if (container) {
        const panzoom: PanzoomObject = Panzoom(container, {
            maxScale: 5,
            animate: false,
            overflow: "hidden",
            startScale: "0.66"
        });

        addPanzoomEvents(inBtnZoomIn, inBtnZoomOut, inBtnResetZoom, container.parentElement!, panzoom);
        return panzoom;
    }

    return undefined;
}

function addPanzoomEvents(inBtnZoomIn: string | undefined, inBtnZoomOut: string | undefined, inBtnResetZoom: string | undefined, containerParent: HTMLElement, panzoom: PanzoomObject): void {
    const eventMapping = [
        { Selector: inBtnZoomIn, PanzoomFunction: panzoom.zoomIn, Type: "Click" },
        { Selector: inBtnZoomOut, PanzoomFunction: panzoom.zoomOut, Type: "Click" },
        { Selector: inBtnResetZoom, PanzoomFunction: panzoom.reset, Type: "Click" },
        { HTMLElement: containerParent, PanzoomFunction: panzoom.zoomWithWheel, Type: "wheel" }
    ];

    eventMapping.map(event => {
        if (event.Selector) {
            const btn: HTMLElement | undefined = jQuery(event.Selector).get(0);
            if (btn)
                btn.addEventListener(event.Type, event.PanzoomFunction);
        }
        else if (event.HTMLElement) {
            if (event.Type === "wheel")
                event.HTMLElement.addEventListener(event.Type, event.PanzoomFunction);
        }
    })
}

export function unbindPanzoomEvents(inSelector: string): void {
    const container: HTMLElement = jQuery(inSelector).get(0);
    container.parentElement?.removeEventListener('wheel', config.state.panzoom!.zoomWithWheel);
}