import { Controller } from '@hotwired/stimulus';

/*
* The following line makes this controller "lazy": it won't be downloaded until needed
* See https://github.com/symfony/stimulus-bridge#lazy-controllers
*/
/* stimulusFetch: 'lazy' */
export default class extends Controller {
    languages = []
    providers = []
    qualities = []
    seasons = []

    activeFilter = {
        "resolution": [],
        "codec": [],
        "language": [],
        "provider": [],
        "quality": [],
    }

    defaultOptions = '<option value="-">-</option>';

    static outlets = ['tv-episode-list']
    static targets = ['resolution', 'codec', 'language', 'provider', 'season', 'quality', 'selectAll', 'downloadSelected', 'currentSeason']
    static values = {
        'imdbId': String,
        'media-type': String,
        'episodes': Array,
        'reverseMappedQualities': Object,
    }

    async connect() {
        await this.setInitialFilter();
        this.element.filterResults = this.filter.bind(this);
        document.addEventListener('optionsLoaded', this.loadOptions.bind(this));
    }

    async setInitialFilter() {
        const response = await fetch('/api/user/filters');
        const filters = await response.json();
        if (filters.length > 0) {
            this.activeFilter = filters[0];
        }
        if (this.mediaTypeValue === "tvshows") {
            this.activeFilter['season'] = 1;
        }
    }

    // Event is fired from movies/tvshows controllers to populate this data
    async loadOptions({detail: { options }}) {
        await options.forEach((option) => {
            option.filter({detail: {activeFilter: this.activeFilter }});
        })
    }

    selectAllEpisodes() {
        document.dispatchEvent(new CustomEvent('selectEpisodeForDownload', {
            detail: {
                select: this.selectAllTarget.checked,
            }
        }));
    }

    downloadSelectedEpisodes() {
        document.dispatchEvent(new CustomEvent('downloadSelectedEpisodes', {}));
    }

    filter() {
        const downloadSeasonSpan = document.querySelector("#downloadSeasonModal");

        this.activeFilter = {
            "resolution": this.#fetchValuesFromNodeList(this.resolutionTarget.selectedOptions),
            "codec": this.#fetchValuesFromNodeList(this.codecTarget.selectedOptions),
            "language": this.#fetchValuesFromNodeList(this.languageTarget.selectedOptions),
            "provider": this.#fetchValuesFromNodeList(this.providerTarget.selectedOptions),
            "quality": this.#fetchValuesFromNodeList(this.qualityTarget.selectedOptions),
        }

        if ("tvshows" === this.mediaTypeValue) {
            downloadSeasonSpan.innerText = this.seasonTarget.value;
            this.activeFilter.season = this.seasonTarget.value;
        }

        const event = new CustomEvent('filterDownloadOptions', {
            detail: {
                activeFilter: this.activeFilter
            }
        })

        // Event is picked up by the episode-container
        // or movie-container web components
        document.dispatchEvent(event);
    }

    setSeason(event) {
        console.log('hurrrr');
        this.tvEpisodeListOutlet.setSeason(event.target.value);
        this.currentSeasonTarget.innerText = event.target.value;
    }

    downloadSeason() {
        fetch(`/api/download/season/${this.imdbIdValue}/${this.activeFilter['season']}`, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
    }

    #fetchValuesFromNodeList(nodeList) {
        return [...nodeList].map(option => option.value)
    }

    #serializeSelectOptions(options) {
        return this.defaultOptions + options.sort()
            .map((option) => {
                return '<option value="' + option + '">' + option + '</option>'
            })
            .join();
    }
}
