import { djbase, djclass } from "@implab/djx/declare";
import { DjxWidgetBase } from "@implab/djx/tsx/DjxWidgetBase";
import { createElement, watch } from "@implab/djx/tsx";
import ProgressBar from "./ProgressBar";
import Button = require("dijit/form/Button");

const ref = <W extends DjxWidgetBase, K extends keyof W>(target: W, name: K) => (v: W[K]) => target.set(name, v);

@djclass
export default class MainWidget extends djbase(DjxWidgetBase) {

    titleNode?: HTMLHeadingElement;

    progressBar?: ProgressBar;

    count = 0;

    showCounter = false;

    render() {
        return <div className="tundra">
            <h2 ref={ref(this, "titleNode")}>Hi!</h2>
            <ProgressBar ref={ref(this, "progressBar")} />
            {watch(this, "showCounter", flag => flag &&
                <section style={{padding: "10px"}}>
                    <label>
                        Counter: {watch(this, "count", v => [<span>{v}</span>, " ", <span>sec</span>])}
                    </label>
                </section>
            )}
            <Button onClick={this._onToggleCounterClick}>Toggle counter</Button>
        </div>;
    }

    postCreate(): void {
        super.postCreate();

        const inc = () => {
            this.set("count", this.count + 1);
            this.defer(inc, 1000);
        }

        inc();
    }

    private _onToggleCounterClick = () => {
        this.set("showCounter", !this.showCounter);
    }
}
