<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>OnTheSpot - Download Queue</title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
        <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
        <script src="{{ url_for('static', filename='utils.js') }}" defer></script>
    </head>
    <body>
        <div class="header">
            <ul>
                <li class="hide-on-mobile"><a href="https://github.com/justin025/onthespot/" target="_blank">OnTheSpot</a></li>
                <li><a class="active" href="/search">Search</a></li>
                <li><a href="/download_queue">Downloads</a></li>
                <li><a href="/settings">Settings</a></li>
                <li><a href="/about">About</a></li>
            </ul>
        </div>

        <br>

        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
            <div style="display: flex; align-items: center;">
                <form onsubmit="submitSearch(event)">
                    <input style="margin-right: 0px;" type="text" id="search-bar" name="q" placeholder="Search by name">
                    <button type="submit">Search</button>
                </form>
            </div>

            <div style="display: flex; align-items: center;">
                <button class="download-action-button"  onclick="toggleVisibility()" class="hide-on-mobile">
                    <img id="collapse_button_icon" src="/icons/collapse_down.png" loading="lazy" style="width: 20px; height: 20px;">
                </button>
            </div>
        </div>

        <div id="toggle_visibility" style="display: none;  margin-top: 20px; margin-bottom: 15px;">
            <hr style="border: 1px solid #fff; margin-bottom: 20px;">
            <div style="display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; align-items: center;">
                    <p style="margin-right: 5px; margin-left: 15px;">Search For:</p>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_tracks">Tracks</label>
                    <input type="checkbox" id="enable_search_tracks" {% if config.enable_search_tracks %}checked{% endif %}>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_albums">Albums</label>
                    <input type="checkbox" id="enable_search_albums" {% if config.enable_search_albums %}checked{% endif %}>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_playlists">Playlists</label>
                    <input type="checkbox" id="enable_search_playlists" {% if config.enable_search_playlists %}checked{% endif %}>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_artists">Artists</label>
                    <input type="checkbox" id="enable_search_artists" {% if config.enable_search_artists %}checked{% endif %}>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_episodes">Episodes</label>
                    <input type="checkbox" id="enable_search_episodes" {% if config.enable_search_episodes %}checked{% endif %}>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_podcasts">Podcasts</label>
                    <input type="checkbox" id="enable_search_podcasts" {% if config.enable_search_podcasts %}checked{% endif %}>
                    <label style="margin-right: 5px; margin-left: 15px;" for="enable_search_audiobooks">Audiobooks</label>
                    <input type="checkbox" id="enable_search_audiobooks" {% if config.enable_search_audiobooks %}checked{% endif %}>
                </div>
                <div style="display: flex; align-items: center;">
                    <button class="download-action-button"  onclick="updateSettings(returnSearchFilters())">
                        <img src="/icons/save.png" loading="lazy" style="width: 20px; height: 20px;">
                    </button>
                </div>
            </div>
        </div>

        <br>

        <table border="1" id="results-table">
            <thead>
                <tr>
                    {% if config.show_search_thumbnails %}
                    <th>Image</th> <!-- This header is shown only if thumbnails are enabled -->
                    {% endif %}
                    <th>Name</th>
                    <th class="hide-on-mobile">By</th>
                    <th>Type</th>
                    <th>Service</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <!-- Results will be populated here -->
            </tbody>
        </table>

        <script>
            function returnSearchFilters() {
                const filterData = {
                    enable_search_tracks: document.getElementById('enable_search_tracks').checked,
                    enable_search_albums: document.getElementById('enable_search_albums').checked,
                    enable_search_artists: document.getElementById('enable_search_artists').checked,
                    enable_search_playlists: document.getElementById('enable_search_playlists').checked,
                    enable_search_episodes: document.getElementById('enable_search_episodes').checked,
                    enable_search_podcasts: document.getElementById('enable_search_podcasts').checked,
                    enable_search_audiobooks: document.getElementById('enable_search_audiobooks').checked,
                    }
                return filterData
                }

            function submitSearch(event) {
                event.preventDefault();
                const query = document.getElementById('search-bar').value;
                fetch(`/api/search_results?q=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        const tableBody = document.getElementById('results-table').getElementsByTagName('tbody')[0];
                        tableBody.innerHTML = '';
                        data.forEach(item => {
                            const showThumbnails = {{ config.show_search_thumbnails|tojson }};

                            const itemImage = showThumbnails && item.item_thumbnail_url
                                ? `<img src="${item.item_thumbnail_url}" loading="lazy" style="width: {{ config.thumbnail_size }}px; height: {{ config.thumbnail_size }}px;">`
                                : '';

                            const serviceIcon = item.item_service
                                ? `<img src="/icons/${item.item_service}.png" loading="lazy" style="width: 20px; height: 20px; margin-right: 5px;">`
                                : '';

                            const serviceNameSpan = document.createElement('span');
                            serviceNameSpan.className = 'hide-on-mobile';
                            serviceNameSpan.textContent = formatServiceName(item.item_service);

                            const copyButton = createButton('icons/link.png', 'Copy Link', `copyToClipboard('${item.item_url}')`, `${item.item_url}`);
                            const downloadButton = createButton('icons/download.png', 'Download', `handleDownload('${item.item_url}')`);


                            const row = document.createElement('tr');

                            // Conditionally create the cell for the image if thumbnails are enabled
                            if (itemImage) {
                                const cellImage = document.createElement('td');
                                cellImage.innerHTML = itemImage; // Insert the item image
                                row.appendChild(cellImage);
                            }

                            // Cell for item name
                            const cell1 = document.createElement('td');
                            cell1.textContent = item.item_name;
                            row.appendChild(cell1);

                            // Cell for item by
                            const cell2 = document.createElement('td');
                            cell2.className = 'hide-on-mobile';
                            cell2.textContent = item.item_by;
                            row.appendChild(cell2);

                            // Cell for item type
                            const cell3 = document.createElement('td');
                            cell3.textContent = capitalizeFirstLetter(item.item_type);
                            row.appendChild(cell3);

                            // Cell for the service icon and name
                            const cell4 = document.createElement('td');
                            cell4.innerHTML = `${serviceIcon}`; // Add the service icon
                            cell4.appendChild(serviceNameSpan); // Append the service name span
                            row.appendChild(cell4);

                            // Cell for copy and download buttons
                            const cell5 = document.createElement('td');
                            cell5.innerHTML = `${copyButton}${downloadButton}`;
                            row.appendChild(cell5);

                            // Append the completed row to the table body
                            tableBody.appendChild(row);
                        });
                });
                document.getElementById('search-bar').value = '';
            }

            function handleDownload(url) {
                fetch(`/api/parse_url/${encodeURIComponent(url)}`, {
                    method: 'POST',
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('Download successful');
                    } else {
                        console.error('Download failed:', data.error);
                    }
                })
                .catch(error => console.error('Error:', error));
            }
        </script>
    </body>
</html>
