<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    {% set page_title = 'File Search Results' %}
    <title>{{ page_title }}</title>

    {% set bloom_mod = 'dewey' %}

    <link rel="stylesheet" type="text/css" href="{{ style.skin_css }}">
    <link rel="stylesheet" type="text/css" href="/static/legacy/style.css">
    <script src="/static/legacy/action_buttons.js"></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/css/selectize.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/js/standalone/selectize.min.js"></script>
    <script>
        function toggleSelectAll(checkboxClass, masterCheckboxId) {
            const checkboxes = document.querySelectorAll(checkboxClass);
            const selectAll = document.getElementById(masterCheckboxId).checked;
            checkboxes.forEach(checkbox => checkbox.checked = selectAll);
            updateColumnGlow(checkboxClass);
        }
        
        function checkConflict(currentCheckbox, checkboxClass) {
            const otherCheckboxes = document.querySelectorAll(checkboxClass);
            if (currentCheckbox.checked) {
                otherCheckboxes.forEach(checkbox => {
                    if (checkbox.checked) {
                        alert('You cannot select files for both download and create set at the same time.');
                        currentCheckbox.checked = false;
                        return;
                    }
                });
            }
            updateColumnGlow('.file-checkbox');
            updateColumnGlow('.file-set-checkbox');
        }
        

        function updateColumnGlow(checkboxClass) {
            const checkboxes = document.querySelectorAll(checkboxClass);
            const anyChecked = Array.from(checkboxes).some(cb => cb.checked);
            const columnClass = checkboxClass === '.file-checkbox' ? 'download-column' : 'file-set-column';
            const columnCells = document.querySelectorAll(`.${columnClass}`);
            
            columnCells.forEach(cell => {
                if (anyChecked) {
                    cell.classList.add('glow');
                } else {
                    cell.classList.remove('glow');
                }
            });
        }

        function createFileSet(event) {
            event.preventDefault(); // Prevent the default form submission
        
            const checkboxes = document.querySelectorAll('.file-set-checkbox:checked');
            const euids = Array.from(checkboxes).map(cb => cb.value).join("\n");
        
            if (!euids) {
                alert("Please select files to create a file set.");
                return;
            }
        
            document.getElementById('file_euids').value = euids;
        
            console.log('Creating file set with EUIDs:', euids);
            document.getElementById('fileSetForm').submit(); // Submit the form for file set creation
        }
        

        function downloadTableAsTSV() {
            const table = document.querySelector('table');
            if (!table) {
                alert('No table found!');
                return;
            }

            let tsv = [];
            const rows = table.querySelectorAll('tr');

            for (const row of rows) {
                const cols = row.querySelectorAll('td, th');
                const rowData = [];
                for (const col of cols) {
                    rowData.push(col.innerText);
                }
                tsv.push(rowData.join('\t'));
            }

            const tsvFile = new Blob([tsv.join('\n')], { type: 'text/tsv' });
            const downloadLink = document.createElement('a');
            const now = new Date();
            const timestamp = now.getFullYear() + "-" +
                              (now.getMonth() + 1).toString().padStart(2, '0') + "-" +
                              now.getDate().toString().padStart(2, '0') + "_" +
                              now.getHours().toString().padStart(2, '0') + "-" +
                              now.getMinutes().toString().padStart(2, '0') + "-" +
                              now.getSeconds().toString().padStart(2, '0');
            downloadLink.download = `dewey_search_${timestamp}.tsv`;
            downloadLink.href = window.URL.createObjectURL(tsvFile);
            downloadLink.style.display = 'none';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        }

        function sortTable(columnIndex) {
            const table = document.querySelector('table');
            const rows = Array.from(table.querySelectorAll('tbody > tr'));
            const header = table.querySelector(`thead > tr > th:nth-child(${columnIndex + 1})`);
            const isAscending = header.classList.contains('ascending');

            rows.sort((a, b) => {
                const aText = a.children[columnIndex].innerText.trim();
                const bText = b.children[columnIndex].innerText.trim();

                if (!isNaN(aText) && !isNaN(bText)) {
                    return isAscending ? aText - bText : bText - aText;
                } else {
                    return isAscending ? aText.localeCompare(bText) : bText.localeCompare(aText);
                }
            });

            rows.forEach(row => table.querySelector('tbody').appendChild(row));
            table.querySelectorAll('thead > tr > th').forEach(th => th.classList.remove('ascending', 'descending'));

            header.classList.toggle('ascending', !isAscending);
            header.classList.toggle('descending', isAscending);
        }
    </script>


    <script>
        
        function updateDependentFields(formContext) {
            function populateSelectField(selectFieldId, options) {
                const selectField = $(`[data-form=${formContext}] #${selectFieldId}`);
                selectField.empty();
                options.forEach(function(option) {
                    selectField.append(new Option(option, option));
                });
                selectField.trigger('change');
            }

            function handleFieldChange(field, dependentField, enumObj, formContext) {
                $(`[data-form=${formContext}] #${field}`).change(function() {
                    const selectedValue = $(this).val();
                    const dependentOptions = enumObj[selectedValue] || [];
                    populateSelectField(dependentField, dependentOptions, formContext);
                });
            }

            Object.keys(controlledProperties).forEach(function(prop) {
                if (controlledProperties[prop].type === "dependent string") {
                    const dependentField = controlledProperties[prop].on;
                    const enumObj = controlledProperties[prop].enum;
                    handleFieldChange(dependentField, prop, enumObj, formContext);
                }
            });
        }

        function filterOptions(event) {
            const input = event.target.value.toLowerCase();
            const selectField = event.target;
            const options = selectField.options;

            for (let i = 0; i < options.length; i++) {
                const optionText = options[i].text.toLowerCase();
                if (optionText.includes(input) || options[i].value === "") {
                    options[i].style.display = "";
                } else {
                    options[i].style.display = "none";
                }
            }
        }

        $(document).ready(function() {
            $('#tag').selectize({
                create: true,
                sortField: [{ field: 'value', direction: 'asc' }],
                placeholder: 'Select or type to add...',
                persist: false,
                render: {
                    option_create: function(data, escape) {
                        return '<div class="create">Create: <strong>' + escape(data.input) + '</strong>&hellip;</div>';
                    }
                }
            });
        });

    </script>
    <style>


        .form-section {
            display: inline-block;
            margin: 0 1.5%;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 5px;
        }

        .form-section label, .form-section input, .form-section select, .form-section textarea {
        }

        .form-group {
            display: flex;
            align-items: center;
        }

        .form-group label {
        }

        .form-group input, .form-group select, .form-group textarea {
            
        }

        .glow {
            box-shadow: 0 0 10px fuchsia;
            transition: box-shadow 0.5s ease-in-out;
        }

        th.ascending::after {
            content: ' \25B2'; /* Up arrow */
        }

        th.descending::after {
            content: ' \25BC'; /* Down arrow */
        }

        .div.selectize-input {
            padding: inherit;
            border: inherit;
            margin: inherit;
            position: inherit;
        }
        .selectize-input {
            padding: inherit;
            border: inherit;
            margin: inherit;
            position: inherit;
            background-color: var(--form-in-bg-color);
        }
    </style>
</head>
<body>
    {% include 'legacy/bloom_header.html' %}

    <b>{{ n_results }} File Search Results</b>
    <form id="fileSetForm" action="/create_file_set" method="post"  >
        <div style="display: flex; flex:none;">
            <div class="form-section" style="background-color: rgba(204, 255, 204, 0.1); flex:none;">
                <h4>Download Selected Files</h4>

                <div class="form-group">
                    
                    <label for="download-type"> Type: </label>
                    <select id="download-type">
                        <option value="dewey" >dewey</option>
                        <option selected value="hybrid">hybrid</option>
                        <option value="orig">orig</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="create-metadata"> Create dewey.yaml Metadata File: </label>
                    <select id="create-metadata">
                        <option value="yes" selected>yes</option>
                        <option value="no">no</option>
                    </select><br>
                    <button type="button" onclick="downloadSelectedFiles()">Download Files</button>

                </div>
            </div>

            <div class="form-section" style="background-color: rgba(204, 255, 204, 0.1);">
                Create File Set (from selected)<br>
                <div class="form-group">
                    {% for field in ui_fields_fset %}
                    <div>
                        {% if field.name == "creating_user" %}
        
                        {% elif field.name == "ref_type" %}
        
                        {% elif field.name == "tags" %}
        
                        {% elif field.type == "select" %}
                            
                              
                            <label for="{{ field.name }}">{{ field.label }}</label>
                            
                            <select data-form="create-fs" name="{{ field.name }}" id="{{ field.name }}" class="select-filter">
                                <option value="" selected></option> <!-- Placeholder for blank state -->
                                {% for option in field.options %}
                                    <option value="{{ option }}">{{ option }}</option>
                                {% endfor %}
                            </select>
        
                        {% else %}
                        <label for="{{ field.name }}">{{ field.label }}</label>
        
                            {% if field.name.endswith('_datetime') %}
                                <input type="date" name="{{ field.name }}" id="{{ field.name }}" />
                            {% else %}
                                <input type="{{ field.type }}" name="{{ field.name }}" id="{{ field.name }}" />
                            {% endif %}
                        {% endif %}
                    </div>
                {% endfor %}
                </div>
                <div class="form-group">
                  
            <br><br>
            <label for="ref_type">Share Files In Set? </label>
            <select id="ref_type" name="ref_type" onchange="toggleRcloneOptions()" >
                <option value="na">Database File Set Only</option>
                <option value="presigned_url">Create Presigned S3 URLS Per File</option>
                <option value="rclone serve http">Share File Set Via HTTP</option>
                <option value="rclone serve sftp">Share File Set Via SFTP</option>

            </select><br>
            <div id="rclone-options" style="display: none;">
                <small><a href=https://rclone.org/commands/rclone_serve/>rclone serve</a> is magic & free</small>
                <br><br>
                bucket:<input type="text" name="bucket" value="{{ s3_bucket_prefix }}"> //
                host:<input type="text" name="host" value="0.0.0.0"> // port:<input type="text" name="port" value="8080"> <br>
                user:<input type="text" name="user" value="user"> // pass:<input type="text" name="passwd" value="passwd">         
            </div>

                        <label for="duration"> Share Duration (days, float acceptable): </label>
                        <input type="text" id="duration" name="duration" value="1" style="width:30px;" >
                        <button onclick="createFileSet(event)">Create File Set</button>

                </div>

               
                <input type="hidden" id="file_euids" name="file_euids">

            </div>
            
            <div class="form-section" style="background-color: rgba(204, 255, 204, 0.1);">
                <small>
                d/l<br>table<br>as<br>TSV<br>
                </small>
                <button type="submit" class="download-tsv" onclick="downloadTableAsTSV()">⬇️</button>
            </div>

        </div>
    </form>
    <table border="1">
        <thead>
            <tr>
                <th onclick="sortTable(0)" class="download-column">
                    <input type="checkbox" id="select-all-download" onclick="toggleSelectAll('.file-checkbox', 'select-all-download')">
                    Flag to download
                </th>
                <th onclick="sortTable(1)" class="file-set-column">
                    <input type="checkbox" id="select-all-file-set" onclick="toggleSelectAll('.file-set-checkbox', 'select-all-file-set')">
                    Create File Set
                </th>
                {% for column in columns %}
                <th onclick="sortTable({{ loop.index + 1 }})">{{ column }}</th>
                {% endfor %}
                <th onclick="sortTable({{ columns|length + 2 }})">S3 URI</th>
            </tr>
        </thead>
        <tbody>
            {% for row in table_data %}
            <tr>
                <td class="download-column"><input type="checkbox" class="file-checkbox" value="{{ row['EUID'] }}" onclick="checkConflict(this, '.file-set-checkbox')"></td>
                <td class="file-set-column"><input type="checkbox" class="file-set-checkbox" value="{{ row['EUID'] }}" onclick="checkConflict(this, '.file-checkbox')"></td>
                {% for column in columns %}
                <td>
                    {% if column == 'EUID' %}
                    <a target="_blank" href="euid_details?euid={{ row[column] }}">{{ row[column] }}</a>
                    {% else %}
                    {{ row[column] }}
                    {% endif %}
                </td>
                {% endfor %}
                <td>{{ row['current_s3_uri'] }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <a href="/dewey">Go Back</a>



    <script>
        async function triggerDownload(url) {
            return new Promise((resolve) => {
                const link = document.createElement('a');
                link.href = url;
                link.download = '';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                resolve();
            });
        }

        async function downloadFile(euid, downloadType, createMetadataFile) {
            console.log(`Downloading file for EUID: ${euid}`);

            const formData = new URLSearchParams();
            formData.append('euid', euid);
            formData.append('download_type', downloadType);
            formData.append('create_metadata_file', createMetadataFile);
            formData.append('ret_json', 'True');

            const response = await fetch(`/download_file`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData.toString()
            });

            if (response.ok) {
                const jsonResponse = await response.json();
                const fileDownloadPath = jsonResponse.file_download_path;
                const metadataDownloadPath = jsonResponse.metadata_download_path;

                console.log('fileDownloadPath:', fileDownloadPath);
                console.log('metadataDownloadPath:', metadataDownloadPath);

                // Trigger downloads
                await triggerDownload(fileDownloadPath);
                if (metadataDownloadPath) {
                    await triggerDownload(metadataDownloadPath);
                }
            } else {
                console.error(`Failed to download file for EUID: ${euid}`);
            }
        }

        async function downloadSelectedFiles() {
            const checkboxes = document.querySelectorAll('.file-checkbox:checked');
            const euids = Array.from(checkboxes).map(cb => cb.value);
        
            const downloadType = document.getElementById('download-type').value;
            const createMetadataFile = document.getElementById('create-metadata').value;
        
            if (euids.length === 0) {
                alert("Please select files to download.");
                return;
            }
        
            console.log('Selected EUIDs:', euids);
        
            for (const euid of euids) {
                await downloadFile(euid, downloadType, createMetadataFile);
            }
        } 

        function sortTable(columnIndex) {
            const table = document.querySelector('table');
            const rows = Array.from(table.querySelectorAll('tbody > tr'));
            const header = table.querySelector(`thead > tr > th:nth-child(${columnIndex + 1})`);
            const isAscending = header.classList.contains('ascending');

            rows.sort((a, b) => {
                const aText = a.children[columnIndex].innerText.trim();
                const bText = b.children[columnIndex].innerText.trim();

                if (!isNaN(aText) && !isNaN(bText)) {
                    return isAscending ? aText - bText : bText - aText;
                } else {
                    return isAscending ? aText.localeCompare(bText) : bText.localeCompare(aText);
                }
            });

            rows.forEach(row => table.querySelector('tbody').appendChild(row));
            table.querySelectorAll('thead > tr > th').forEach(th => th.classList.remove('ascending', 'descending'));

            header.classList.toggle('ascending', !isAscending);
            header.classList.toggle('descending', isAscending);
        }
    </script>


<script>
    function toggleRcloneOptions() {
        var refType = document.getElementById("ref_type").value;
        var rcloneOptions = document.getElementById("rclone-options");
        
        if (refType.startsWith("rclone")) {
            rcloneOptions.style.display = "block";
        } else {
            rcloneOptions.style.display = "none";
        }
    }

    // Call the function on page load to set the correct state
    document.addEventListener("DOMContentLoaded", function() {
        toggleRcloneOptions();
    });
</script>

    {% include 'legacy/pre_body_close.html' %}
</body>
</html>
