export default class EpisodeContainer extends HTMLElement {
    options = [];
    showTitle;

    #episodeSelectorEl;
    #resultsToggleBtnEl;
    #resultsTableEl;
    #resultsCountBadgeEl;
    #resultsCountNumberEl;

    constructor() {
        super();
        this.showTitle = this.getAttribute('show-title');
        this.#resultsTableEl = this.querySelector('.results-container');
        this.#resultsToggleBtnEl = this.querySelector('.dropdown-button');
        this.#resultsCountBadgeEl = this.querySelector('.results-count-badge');
        this.#resultsCountNumberEl = this.querySelector('.results-count-number');
        this.#episodeSelectorEl = this.querySelector('.episode-selector');

        this.#resultsToggleBtnEl.addEventListener('click', () => this.toggleResults());
        this.#resultsCountBadgeEl.addEventListener('click', () => this.toggleResults());

        document.addEventListener('filterDownloadOptions', this.filter.bind(this));
        document.addEventListener('downloadSelectedEpisodes', this.downloadSelectedResults.bind(this));
        document.addEventListener('selectEpisodeForDownload', (e) => this.selectEpisodeForDownload(e.detail.select));
    }

    toggleResults() {
        this.#resultsToggleBtnEl.classList.toggle('rotate-90');
        this.#resultsToggleBtnEl.classList.toggle('-rotate-90');
        this.#resultsTableEl.classList.toggle('hidden');
    }

    selectEpisodeForDownload(select) {
        if (this.#episodeSelectorEl.disabled === false) {
            this.#episodeSelectorEl.checked = select;
        }
    }

    downloadSelectedResults() {
        if (this.#episodeSelectorEl.disabled === false &&
            this.#episodeSelectorEl.checked === true
        ) {
            console.log('episode is selected')
            this.options.forEach(option => {
                if (option.isSelected === true) {
                    option.download();
                }
                option.isSelected = false;
            })
        }
    }

    filter({ detail: { activeFilter } }) {
        let firstIncluded = true;
        let count = 0;
        let selectedCount = 0;

        this.options.forEach((option) => {
            const include = option.filter({ detail: { activeFilter: activeFilter } });

            if (false === include) {
                option.classList.remove('r-tablerow');
                option.classList.add('hidden');
            } else if (true === firstIncluded) {
                count = 1;
                selectedCount = selectedCount + 1;
                option.querySelector('input[type="checkbox"]').checked = true;
                firstIncluded = false;
            } else {
                count = count + 1;
            }
        });
        this.#resultsCountNumberEl.innerText = count;
    }
}
