
import { loadState } from '@nextcloud/initial-state'
import axios from '@nextcloud/axios'
import { showSuccess, showError } from '@nextcloud/dialogs'


function main() {
    // Get the data injected via the Initial State mechanism
    const state = loadState('ndp', 'my_initial_state');

    // Get the container from the template (/templates/myMainTemplate.php)
    const myDiv = document.querySelector('#app-content #ndp');

    // Add buttons for reports
    addReports(myDiv, state);

    // Add the download button
    addDownloadButton(myDiv);
}

function addReports(container, state) {
    const fileNameList = state.file_name_list;

    // For each file, create a button
    fileNameList.forEach(name => {
        const button = createButton(name);
        button.addEventListener('click', () => {
            downloadFile(name);
        });

        container.appendChild(button);
    });
}

function addDownloadButton(container) {
    // Add a download button
    const downloadButton = createButton('Download Files');
    downloadButton.addEventListener('click', () => {
        downloadFiles(state.file_name_list);
    });

    container.appendChild(downloadButton);
}

function createButton(label) {
    const button = document.createElement('button');
    button.innerText = label;
    button.classList.add('report-button'); // Add a class for styling if needed
    return button;
}

function downloadFile(fileName) {
    axios.get(`/index.php/apps/ndp/download/${fileName}`)
        .then(response => {
            showSuccess('Downloaded ' + response.data.message);
        })
        .catch(error => {
            showError('Failed to download ' + error.response.data.error_message);
            console.error(error);
        });
}

function downloadFiles(fileList) {
    fileList.forEach(fileName => {
        downloadFile(fileName);
    });
}

document.addEventListener('DOMContentLoaded', main);
