import { DOM, configure, IElement, template, bindable, MF, customElement, containerfree, IBindingContext } from 'mframejs';
import { JSDOM } from 'jsdom';


// our dummy app to simplify parts
export class App implements IElement {
    public loadTemplate() {
        return template`
                <input class="inputs" type="checkbox" checked.bind="checked">
                <br>
                <custom-element
                    repeat.for="$ss of 3"
                    if.bind="checked"
                    text.bind="@{checked}">
                    wow
                </custom-element>`;
    }
}


@containerfree()
@customElement('custom-element')
export class CustomElement implements IElement {

    // default variables every element gets
    public $element: HTMLElement;
    public $bindingContext: IBindingContext;
    public $attributes: NamedNodeMap;

    // private vars
    @bindable() public text = 'hello world';

    // mandatory function/ this can also return promise<string>
    public loadTemplate() {
        return template`
            <div repeat.for="$x of 3">
                @{text + ' ' + $x}
            </div>`;
    }

}


describe('template with repeat and if.bind', () => {

    beforeAll(() => {
        const window = new JSDOM('').window;
        DOM.setConfig(window, window.document);
        configure(App).then((mf: MF) => {
            mf.start(DOM.document.body);
        });

    });


    it('default starts with 2 elemnts', async () => {
        await DOM.waitFor(0);
        // const input = DOM.document.getElementsByClassName('inputs');
        expect(DOM.document.body.children.length).toBe(2);
    });

    it('default starts with 6 child nodes', async () => {
        await DOM.waitFor(0);
        expect(DOM.document.body.childNodes.length).toBe(6);
    });

    it('enabled to be 11 and 24', async () => {
        const input = DOM.document.getElementsByClassName('inputs');
        const event = new (DOM.window as any).CustomEvent('click');
        (input[0] as any).checked = true;
        (input[0]).dispatchEvent(event);
        await DOM.waitFor(0);
        expect(DOM.document.body.children.length).toBe(11);
        expect(DOM.document.body.childNodes.length).toBe(24);
    });

    it('disable to be 2 and 6', async () => {
        const input = DOM.document.getElementsByClassName('inputs');
        const event = new (DOM.window as any).CustomEvent('click');
        (input[0] as any).checked = false;
        (input[0]).dispatchEvent(event);
        await DOM.waitFor(0);
        expect(DOM.document.body.children.length).toBe(2);
        expect(DOM.document.body.childNodes.length).toBe(6);
    });



});
