import { djbase, djclass, bind, prototype, AbstractConstructor } from "../declare";

import { DjxWidgetBase } from "../tsx/DjxWidgetBase";
import { createElement, on } from "../tsx";
import { argumentNotNull } from "@implab/core-amd/safe";

interface MyWidgetAttrs {
    title: string;

    counter: number;
}

interface MyWidgetEvents {
    "count-inc": Event & {
        detail: number;
    };

    "count-dec": Event & {
        detail: number;
    };
}

interface FrameProps {
    ref?: JSX.Ref<HTMLDivElement>;
    children?: unknown[];
}

const Frame = ({children, ref}: FrameProps) => <div ref={ref} >{children}</div>;

@djclass
export class MyWidget extends djbase(DjxWidgetBase as AbstractConstructor<DjxWidgetBase<MyWidgetAttrs, MyWidgetEvents>>) {

    @bind({ node: "titleNode", type: "innerHTML" })
    title = "";

    @prototype(0)
    counter = 0;

    frameNode?: HTMLDivElement;

    render() {

        return <div className="myWidget" onsubmit={this._onSubmit} tabIndex={3} style={{ alignContent: "center", border: "1px solid" }} >
            <h1 data-dojo-attach-point="titleNode"></h1>
            <Frame ref={this._setFrameElement}>
                <span class="up-button" onclick={this._onIncClick}>[+]</span>
                <span class="down-button" onclick={() => this._onDecClick()}>[-]</span>
            </Frame>
        </div>;
    }

    private readonly _setFrameElement = (node?: HTMLDivElement) => {
        this.frameNode = node;
    };

    postCreate() {
        super.postCreate();

        this.on("click", () => {});
    }

    private readonly _onSubmit = (evt: Event) => {
        argumentNotNull(evt, "evt");
    };

    private readonly _onIncClick = (evt: MouseEvent) => {
        argumentNotNull(evt, "evt");

        this.set("counter", this.counter + 1);

        this.emit("count-inc", { bubbles: false });
    };

    _onDecClick() {
        this.emit("count-dec", { bubbles: false, detail: this.counter });
    }

    @on("count-inc")
    protected _onCounterInc(evt: Event & { detail: number; x?: number; }) {
        argumentNotNull(evt, "evt");
    }

    @on("click", "keydown")
    protected _onClick(evt: MouseEvent | KeyboardEvent) {
        argumentNotNull(evt, "evt");
    }
}