export default class DownloadMediaButon extends HTMLElement
{
    #filterEl;
    #mediaType;
    #imdbId;
    #season = null;
    #episode = null;

    connectedCallback() {
        this.#filterEl = this.querySelector('#filter');
        this.#mediaType = this.getAttribute('media-type');
        this.#imdbId = this.getAttribute('imdb-id');

        if (this.getAttribute('season') !== null && this.getAttribute('episode') !== null) {
            this.#season = this.getAttribute('season');
            this.#episode = this.getAttribute('episode');
        } else if (this.#mediaType === 'tvshows') {
            console.warn('Season and Episode are not set for \'tvshows\' media type');
        }
        this.addEventListener('click', this.download.bind(this));
    }

    disconnectedCallback() {
        this.removeEventListener('click', this.download.bind(this));
    }

    connectedMoveCallback() {}

    download() {
        const preferencesForm = document.querySelector('[name="user_media_preferences_form"]');
        const preferences = {
            resolution: preferencesForm.querySelector('[id="user_media_preferences_form_resolution"]').value,
            codec: preferencesForm.querySelector('[id="user_media_preferences_form_codec"]').value,
            language: preferencesForm.querySelector('[id="user_media_preferences_form_language"]').value,
            quality: preferencesForm.querySelector('[id="user_media_preferences_form_quality"]').value,
            provider: preferencesForm.querySelector('[id="user_media_preferences_form_provider"]').value,
        }
        console.log(preferences);
        fetch('/api/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            body: JSON.stringify({
                mediaType: this.#mediaType,
                imdbId: this.#imdbId,
                season: this.#season,
                episode: this.#episode,
                filter: preferences,
            })
        })
            .then(res => res.json())
            .then(json => {
                console.log(json)
            })
    }
}
