import { IDisposable } from "@web-atoms/core/dist/core/types";
import { AtomControl } from "@web-atoms/core/dist/web/controls/AtomControl";
import LogViewStyle from "./LogViewStyle";

export default class LogView extends AtomControl {

    public logs: any[];

    private oldLogItems: IDisposable;
    public get logItems() {
        return this.logs;
    }
    public set logItems(v: any[]) {
        if (this.oldLogItems) {
            this.oldLogItems.dispose();
            this.element.innerHTML = "";
        }
        if (!v) {
            return;
        }
        let last: HTMLElement = null;
        for (const iterator of v) {
            last = this.appendLogItem(iterator);
        }
        last?.scrollIntoView();
        this.oldLogItems = this.registerDisposable(v.watch((t, k, i, item) => {
            if (k === "add") {
                this.appendLogItem(item)?.scrollIntoView();
            }
        }));
    }

    public create() {
        this.defaultControlStyle = LogViewStyle;
        this.logs = null;
        this.element.className = `${this.controlStyle.name} log-view`;
        this.bind(this.element, "logItems", [["this", "logs"]], false, null, this);
    }

    private appendLogItem(log: any): HTMLElement {
        if (log  === null || log === undefined) {
            return;
        }
        if (typeof log === "string") {
            const pre = document.createElement("pre");
            pre.textContent = log;
            this.element.appendChild(pre);
            return pre;
        }
        if (Array.isArray(log)) {
            // if it has only single item...
            if (log.length === 1) {
                return this.appendLogItem(log[0]);
            }
            const map = log.join(", ");
            return this.appendLogItem(map);
        }
        return this.appendLogItem(JSON.stringify(log, undefined, 2));
    }

}
