import { expect } from 'chai';
import { ItemFilter } from './item-filter';

describe('item-filter', () => {

    let globalDomContainer;
    beforeEach(() => {
        globalDomContainer = document.createElement('div');
        document.body.appendChild(globalDomContainer);
    });
    afterEach(() => {
        document.body.removeChild(globalDomContainer);
    });

    /**
     * @param {HTMLInputElement} input
     * @param {string} value
     */
    function type(input, value) {
        input.value = value;
        const event = document.createEvent('CustomEvent');
        event.initCustomEvent('input', true, true, {});
        input.dispatchEvent(event);
    }

    /**
     * @param {string[]} items
     * @param {object} attributes
     * @returns {object}
     */
    function initialize(items, attributes = {}) {
        const itemMarkup = items
            .map(item => `<li data-item-filter-value="${item}">${item}</li>`)
            .join('\n');

        const container = document.createElement('div');
        globalDomContainer.appendChild(container);
        Object.keys(attributes)
            .forEach(key => container.setAttribute(key, attributes[key]));
        container.innerHTML = `
            <input id="list-query" data-item-filter data-item-filter-target="#list-container">
            
            <ul data-item-filter.item-container="list" id="list-container">
                ${itemMarkup}
            </ul>
        `;

        const itemFilter = new ItemFilter(container.querySelector('#list-query'));
        const elements = {
            listQuery: container.querySelector('#list-query'),
            listContainer: container.querySelector('#list-container'),
        };

        items.forEach(item => elements[item] = container.querySelector(`[data-item-filter-value="${item}"]`));
        return { itemFilter, container, ...elements };
    }

    it('should filter the list when typing', () => {
        const { foo, bar, baz, listQuery } = initialize([ 'foo', 'bar', 'baz' ]);
        expect(foo.style.display).to.not.equal('none');
        expect(bar.style.display).to.not.equal('none');
        expect(baz.style.display).to.not.equal('none');
        type(listQuery, 'ba');
        expect(foo.style.display).to.equal('none');
        expect(bar.style.display).to.not.equal('none');
        expect(baz.style.display).to.not.equal('none');
    });

    it('should ignore casing when searching', () => {
        const { foo, bar, baz, listQuery } = initialize([ 'foo', 'bar', 'baz' ]);
        type(listQuery, 'FoO');
        expect(foo.style.display).to.not.equal('none');
        expect(bar.style.display).to.equal('none');
        expect(baz.style.display).to.equal('none');
    });

});
