/src/fragmentmanager.ts
interface TagProperties {
    [key: string]: string
}

function getNode(node: string | HTMLElement) {
    if (typeof node == 'string') {
        return document.getElementById(node);
        if (!node) {
            throw new Error('Could not find destination node ' + node);
        }
    }

    return node;
}

export default class FragmentManager {
    elem: HTMLElement

    constructor(html: string, tagName: string = 'div', tagProperties: TagProperties = {}) {
        this.elem = document.createElement(tagName);
        for (let k of Object.keys(tagProperties)) {
            this.elem.setAttribute(k, tagProperties[k]);
        }
        this.elem.innerHTML = html;
    }

    mount(destNode: string | HTMLElement) {
        getNode(destNode).appendChild(this.elem);
    }

    /* mountInto puts the children into the specified node. Because this
     * adopts an existing node, be careful when unmounting. */
    mountInto(destNode: string | HTMLElement) {
        destNode = getNode(destNode);
        while (this.elem.firstChild) {
            destNode.appendChild(this.elem.firstChild);
        }
        this.elem = destNode;
    }

    unmount() {
        if (this.elem.parentNode)
            this.elem.parentNode.removeChild(this.elem);
    }

    q(query: string) {
        return this.elem.querySelector(query);
    }
}