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 targets = ['monitorList']

    monitorListTargetConnected(target) {
        let monitors = this.element.querySelectorAll('tbody tr');

        monitors.forEach(monitor => {
            monitor.addEventListener('click', (event) => {
                let content, heading = ""
                if (event.target.tagName !== "TR") {
                    content = event.target.parentElement.previewContent;
                    heading = "Monitor for \"" + event.target.parentElement.mediaTitle+ "\"";
                } else {
                    content = event.target.previewContent;
                    heading = "Monitor for \"" + event.target.mediaTitle + "\"";
                }

                if (null !== content && undefined !== content && "" !== content) {
                    if (['', null, undefined].includes(monitor.getAttribute('parent-id'))) {
                        window.location.href = `/monitors/${monitor.getAttribute('monitor-id')}`;
                    } else {
                        document.dispatchEvent(new CustomEvent('showPreviewContentModal', {detail: {heading: heading, content: content}}))
                    }

                }
            })
        })
    }

    deleteMonitor(data) {
        fetch(`/api/monitor/${data.params.id}`, {method: 'DELETE'})
            .then(res => res.json())
            .then(json => console.debug(json));
    }
}
