"use strict";

class TextManager {
    _canvas;
    _textElement;
    _textRect = new TextRect();

    constructor(canvas) {
        this._canvas = canvas;
        
        const container = canvas.parentElement;
        this._textElement = document.createElement("label");
        container.appendChild(this._textElement);
    }

    showText(text) {
        // Fixes the annoying shimmering in the browser debugger
        if (text !== this._textElement.innerHTML) {
            this._textElement.innerHTML = text;
            this._updateDimensions();
        }
    }

    setScale(scale) {
        const baseSize = 80;
        this._textElement.style.fontSize = `${baseSize * scale}px`;
        this._updateDimensions();
    }

    getTextRect(width, height) {
        const canvasRect = this._canvas.getBoundingClientRect();

        // Internal text rect scaled by the currenty dimensions of the canvas
        const canvasWidth = canvasRect.right - canvasRect.left;
        const canvasHeight = canvasRect.bottom - canvasRect.top;
        const rect = new TextRect();
        rect.left = width * (this._textRect.left - canvasRect.left) / canvasWidth;
        rect.top = height * (this._textRect.top - canvasRect.top) / canvasHeight;
        rect.right = width * (this._textRect.right - canvasRect.left) / canvasWidth;
        rect.bottom = height * (this._textRect.bottom - canvasRect.top) / canvasHeight;

        return rect;
    }

    _updateDimensions() {
        const rect = this._textElement.getBoundingClientRect();
        const textRect = this._textRect;
        textRect.left = rect.left;
        textRect.top = rect.top;
        textRect.right = rect.right;
        textRect.bottom = rect.bottom;
    }

}

class TextRect {
    left;
    top;
    right;
    bottom;

    get width() {
        return this.right - this.left;
    }

    get height() {
        return this.bottom -this.top;
    }
}