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, season: String, episode: String, active: Boolean, }; static targets = ['list', 'count', 'episodeSelector'] static outlets = ['loading-icon'] options = [] optionsLoaded = false async connect() { await this.setOptions(); } async setOptions() { if (true === this.activeValue) { await fetch(`/torrentio/tvshows/${this.tmdbIdValue}/${this.imdbIdValue}/${this.seasonValue}/${this.episodeValue}`) .then(res => res.text()) .then(response => { this.element.innerHTML = response; this.options = this.element.querySelectorAll('tbody tr'); if (this.options.length > 0) { this.options.forEach((option) => option.querySelector('.download-btn').dataset['title'] = this.titleValue); this.options[0].querySelector('input[type="checkbox"]').checked = true; } else { this.episodeSelectorTarget.disabled = true; } this.optionsLoaded = true; this.loadingIconOutlet.increaseCount(); }); } } async setActive() { this.activeValue = true; this.element.classList.remove('hidden'); if (false === this.optionsLoaded) { await this.setOptions(); } } setInActive() { this.activeValue = false; this.episodeSelectorTarget.checked = false; this.element.classList.add('hidden'); } isActive() { return this.activeValue; } isSelected() { return this.episodeSelectorTarget.checked; } selectEpisodeForDownload() { if (true === this.isActive() && this.episodeSelectorTarget.disabled === false) { this.episodeSelectorTarget.checked = !this.episodeSelectorTarget.checked; } } toggleList() { this.listTarget.classList.toggle('hidden'); } download() { this.options.forEach(option => { const optionSelector = option.querySelector('input[type="checkbox"]'); if (true === optionSelector.checked) { const downloadBtn = option.querySelector('button.download-btn'); const downloadBtnController = this.application.getControllerForElementAndIdentifier(downloadBtn, 'download-button'); downloadBtnController.download(); optionSelector.checked = false; this.episodeSelectorTarget.checked = false; } }) } }