// #region Imports
import { on } from '@breadstone/mosaik-elements';
import { DomServiceLocator } from '../../Dom/Dom';
import { ControllerBase } from './Abstracts/ControllerBase';
import { RendererServiceLocator } from '../../Dom/Renderer';
/**
 * @public
 */
export class OverflowController extends ControllerBase {
    // #region Fields
    _callback;
    _target;
    _resizeSubscription;
    // #endregion
    // #region Ctor
    constructor(host, config) {
        super(host);
        this._callback = config?.callback;
        this._target = config?.target;
        this._resizeSubscription = null;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    hostConnected() {
        this._resizeSubscription = on(document, 'resize', () => this.onResize());
    }
    /**
     * @public
     * @override
     */
    hostDisconnected() {
        this._resizeSubscription?.dispose();
    }
    /**
     * @private
     */
    onResize() {
        const target = this.tryGetElement(this._target);
        if (target) {
            const isScrollable = this.isScrollable(target);
            this._callback?.(isScrollable);
            if (isScrollable && target.childElementCount) {
                const size = offsetSize(target);
                Array.from(target.children).forEach((x) => {
                    const childPosition = offsetPointRelativeTo(x, target);
                    const childSize = offsetSize(x);
                    if (Math.round(size.width) < Math.round(childPosition.x + childSize.width)) {
                        RendererServiceLocator.current.setAttribute(x, 'hidden');
                    }
                    else {
                        RendererServiceLocator.current.removeAttribute(x, 'hidden');
                    }
                });
            }
        }
    }
    isScrollable(element) {
        return element.clientWidth < element.scrollWidth;
    }
    tryGetElement(elementOrSelector) {
        if (typeof elementOrSelector === 'string') {
            return DomServiceLocator.current.findDescendant(this.host, elementOrSelector);
        }
        return elementOrSelector ?? null;
    }
}
export function offsetPoint(self) {
    return {
        x: self.offsetLeft,
        y: self.offsetTop
    };
}
export function offsetPointRelativeTo(self, parent) {
    const selfPosition = offsetPoint(self);
    const parentPosition = offsetPoint(parent);
    return {
        x: selfPosition.x - parentPosition.x,
        y: selfPosition.y - parentPosition.y
    };
}
export function offsetSize(self) {
    return {
        width: self.offsetWidth,
        height: self.offsetHeight
    };
}
//# sourceMappingURL=OverflowController.js.map