import { rectangle_to_aabb } from "../../core/geom/2d/rectangle_to_aabb.js";
import Vector2 from "../../core/geom/Vector2.js";
import { position_box_next_to_box } from "../../core/graph/layout/box/position_box_next_to_box.js";
import { CompassArrowView } from "../elements/CompassArrowView.js";
import EmptyView from "../elements/EmptyView.js";
import { html_element_to_aabb } from "../html_element_to_aabb.js";
import View from "../View.js";


class TooltipView extends View {
    /**
     *
     * @param {VisualTip} tip
     * @param {View} contentView
     * @constructor
     */
    constructor(tip, contentView) {
        super();


        /**
         *
         * @type {VisualTip}
         */
        this.model = tip;

        //set dom element
        this.el = document.createElement('div');
        this.addClass("tooltip-view");

        const vContents = new EmptyView({ classList: ['contents'] });

        this.addChild(vContents);

        vContents.addChild(contentView);

        this.contentView = vContents;


        const vCompass = new CompassArrowView();

        this.addChild(vCompass);

        this.compass = vCompass;
    }

    /**
     *
     * @param {AABB2} bounds
     */
    layout(bounds) {
        const tipBox = html_element_to_aabb(this.contentView.el);

        const SPACING = 16;

        tipBox.grow(SPACING);

        /**
         *
         * @type {VisualTip}
         */
        const tip = this.model;

        const tipTarget = tip.target;

        const target = rectangle_to_aabb(tipTarget);

        const box = position_box_next_to_box(tipBox, target, bounds);

        box.shrink(SPACING);

        const compass = this.compass;

        function setCompass() {

            const targetCenter = target.getCenter();

            const tipPoint = new Vector2();

            box.computeNearestPointToPoint(targetCenter, tipPoint);

            compass.rotateFromDirectionVector(targetCenter.x - tipPoint.x, targetCenter.y - tipPoint.y);

            compass.position.copy(tipPoint)._add(-box.x0, -box.y0);
        }

        setCompass();

        this.position.set(box.x0, box.y0)
    }
}


export default TooltipView;
