import { controls } from "./controls.js";

export class Cam {
    constructor(options = {}) {
        this.x = 0;
        this.y = 0;
        this.zoom = 2;
        this.homeX = 0;
        this.homeY = 0;
        this.lastMouseX = 0;
        this.lastMouseY = 0;
    }

    update(options = {}) {
        const allowPan = options.allowPan ?? true;
        const allowZoom = options.allowZoom ?? true;
        if (allowZoom && controls.mouse.wheel.deltaY < 0) {
            this.zoomIn();
        } else if (allowZoom && controls.mouse.wheel.deltaY > 0) {
            this.zoomOut();
        }
        if (allowPan && controls.mouse.buttons.left) {
            this.x += (controls.mouse.x - this.lastMouseX) / this.zoom;
            this.y += (controls.mouse.y - this.lastMouseY) / this.zoom;
        }
        this.lastMouseX = controls.mouse.x;
        this.lastMouseY = controls.mouse.y;
    }

    setHome(x,y) {
        this.homeX = x;
        this.homeY = y;
    }

    home() {
        this.x = this.homeX;
        this.y = this.homeY;
    }

    getPosition() {
        return { x: this.x, y: this.y };
    }

    zoomIn() {
        this.setZoomAtMouse(Math.min(this.zoom * 2, 16));
    }

    zoomOut() {
        this.setZoomAtMouse(Math.max(this.zoom / 2, 0.25));
    }

    setZoomAtMouse(nextZoom) {
        if (nextZoom === this.zoom) {
            return;
        }

        const mouseX = controls.mouse.x;
        const mouseY = controls.mouse.y;
        const worldX = mouseX / this.zoom - this.x;
        const worldY = mouseY / this.zoom - this.y;

        this.zoom = nextZoom;
        this.x = mouseX / this.zoom - worldX;
        this.y = mouseY / this.zoom - worldY;
    }
}

export const cam = new Cam();