/**
 * @license
 * Copyright Tyler Technologies, Inc. 
 * License: Apache-2.0
 */
import { removeAllChildren, removeElement } from '@tylertech/forge-core';
export class BaseComponentDelegate {
    get element() {
        return this._element;
    }
    constructor(_config = {}) {
        this._config = _config;
        this._initialize();
    }
    destroy() {
        this.disconnect();
    }
    disconnect() {
        if (!this._element.isConnected) {
            return;
        }
        removeElement(this._element);
    }
    _initialize() {
        var _a, _b, _c, _d;
        this._element = this._build();
        if (!this._element) {
            throw new Error(`Invalid component instance: ${this._element}`);
        }
        this._applyProps();
        this._applyStyle();
        this._applyAttrs();
        (_b = (_a = this._config.options) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.append(this._element);
        if ((_c = this._config.options) === null || _c === void 0 ? void 0 : _c.children) {
            this._applyChildren();
        }
        (_d = this._configure) === null || _d === void 0 ? void 0 : _d.call(this);
    }
    _applyProps() {
        if (this._config.props) {
            Object.assign(this._element, this._config.props);
        }
    }
    _applyStyle() {
        var _a, _b;
        if ((_a = this._config.options) === null || _a === void 0 ? void 0 : _a.style) {
            const keys = Object.keys(this._config.options.style);
            for (const key of keys) {
                (_b = this._element) === null || _b === void 0 ? void 0 : _b.style.setProperty(key, this._config.options.style[key]);
            }
        }
    }
    _applyAttrs() {
        var _a, _b;
        if ((_a = this._config.options) === null || _a === void 0 ? void 0 : _a.attributes) {
            if (this._config.options.attributes instanceof Map) {
                for (const [key, value] of Array.from(this._config.options.attributes)) {
                    this._element.setAttribute(key, value);
                }
            }
            else {
                const keys = Object.keys(this._config.options.attributes);
                for (const key of keys) {
                    (_b = this._element) === null || _b === void 0 ? void 0 : _b.setAttribute(key, this._config.options.attributes[key]);
                }
            }
        }
    }
    _applyChildren() {
        var _a;
        if (this._element.hasChildNodes()) {
            removeAllChildren(this._element);
        }
        if (!((_a = this._config.options) === null || _a === void 0 ? void 0 : _a.children)) {
            return;
        }
        if (typeof this._config.options.children === 'string') {
            this._element.innerHTML = this._config.options.children;
        }
        else {
            this._element.appendChild(this._config.options.children);
        }
    }
}
