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 {
    H264_CODECS = ['h264', 'h.264', 'x264']
    H265_CODECS = ['h265', 'h.265', 'x265', 'hevc']

    static values = {
        title: String,
        tmdbId: String,
        imdbId: String
    };

    static targets = ['list']

    options = []
    optionsLoaded = false

    async connect() {
        await this.setOptions();
    }

    async setOptions() {
        if (false === this.optionsLoaded) {
            this.optionsLoaded = true;
            await fetch(`/torrentio/movies/${this.tmdbIdValue}/${this.imdbIdValue}`)
                .then(res => res.text())
                .then(response => {
                    this.element.innerHTML = response;
                    this.options = this.element.querySelectorAll('tbody tr');
                    this.options.forEach((option) => option.querySelector('.download-btn').dataset['title'] = this.titleValue);
                });
        }
    }

    // Keeps compatible with Filter & TV Shows
    isActive() {
        return true;
    }

    async filter(activeFilter) {
        let firstIncluded = true;
        let count = 0;
        let selectedCount = 0;

        this.options.forEach((option) => {
            const props = {
                "resolution": option.querySelector('#resolution').textContent.trim(),
                "codec": option.querySelector('#codec').textContent.trim(),
                "provider": option.querySelector('#provider').textContent.trim(),
                "languages": JSON.parse(option.dataset['languages']),
            }

            let include = true;
            option.classList.remove('hidden');
            option.querySelector('input[type="checkbox"]').checked = false;

            for (let [key, value] of Object.entries(activeFilter)) {
                if (value === "" || key === "season") {
                    continue;
                }
                if (key === "codec" && value === "h264") {
                    if (!this.H264_CODECS.includes(props[key].toLowerCase())) {
                        include = false;
                    }
                } else if (key === "codec" && value === "h265") {
                    if (!this.H265_CODECS.includes(props[key].toLowerCase())) {
                        include = false;
                    }
                } else if (key === "language") {
                    if (!props["languages"].includes(value)) {
                        include = false;
                    }
                } else if (props[key] !== value) {
                    include = false;
                }
            }

            if (false === include) {
                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;
            }
        });
    }
}
