import { djbase, djclass } from "@implab/djx/declare";
import { DjxWidgetBase } from "@implab/djx/tsx/DjxWidgetBase";
import { bind, createElement, prop, watch, watchFor } from "@implab/djx/tsx";
import MainModel from "../model/MainModel";
import { OrderUpdate, Observable } from "@implab/djx/observable";
import { Appointment } from "../model/Appointment";
import { LocalDate } from "@js-joda/core";
import Button = require("dijit/form/Button");

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

    appointments?: Observable<OrderUpdate<Appointment>>;

    model: MainModel;

    dateTo?: LocalDate;

    dateFrom?: LocalDate;

    constructor(opts?: Partial<MainWidget> & ThisType<MainWidget>, srcNode?: string | Node) {
        super(opts, srcNode);

        const model = this.model = new MainModel();
        this.own(model);
        model.subscribe({ next: x => this.set(x) });
    }


    render() {

        return <div className="tundra">
            <h2 ref={bind("innerHTML", prop(this, "title"))} />
            {watch(prop(this, "appointments"), items => items &&
                <ul>
                    {watchFor(items, ({ id, title, getMembers }) =>
                        <li>{title}
                            <ul>
                                {watchFor(getMembers(), ({ role, name, position }) =>
                                    <li className={role}>{name}({position})</li>
                                )}
                            </ul>
                            <div>
                                <Button onClick={() => this._onAddMemberClick(id)}>Add member</Button>
                            </div>
                        </li>
                    )}
                </ul>
            )}
            <div>
                <Button onClick={this._onAddAppointmentClick}>Add new appointment</Button>
            </div>
        </div>;
    }

    load() {
        this.model.load();
    }

    private readonly _onAddMemberClick = (appointmentId: string) => {
        this.model.addMember(appointmentId, {
            email: "some-mail",
            name: "Member Name",
            position: "Member position",
            role: "participant"
        });
    };

    private readonly _onAddAppointmentClick = () => {
        this.model.addAppointment("Appointment", new Date, 30);
    };
}
