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 {
    static values = {
        title: String,
        tmdbId: String,
        imdbId: String
    };

    static targets = ['list']

    options = []
    optionsLoaded = false
    resultCountEl = null

    async connect() {
        this.resultCountEl = document.querySelector('#movie_results_count');
    }

    async listTargetConnected() {
        this.optionsLoaded = true;
        this.options = this.element.querySelectorAll('tbody tr');
        this.options.forEach((option) => option.querySelector('.download-btn').dataset['title'] = this.titleValue);
        this.resultCountEl.innerText = this.options.length;
        document.dispatchEvent(new CustomEvent('optionsLoaded', {detail: {options: this.options}}));
    }
}
