'use strict';

/**
 * Updates the content of a publication by ID
 * 
 * @param {int} publicationId - Publication ID to update
 */
function update(publicationId) {

    // Getting the DOM elements of the post's title and content, image
    const publicationTitle = document.getElementById('publication-title-' + publicationId)
    const publicationContent = document.getElementById('publication-content-' + publicationId)
    const publicationImage = document.getElementById('img-' + publicationId)

    // Requesting a new title from the user
    let title = prompt('Введите название для публикации', publicationTitle.textContent.trim())

    //Checking that the title is not empty
    if (!title.trim()) {
        alert('Заголовок не может быть пустыми!');
        return;

    } else {
        // Requesting a new content from the user
        let content = prompt('Введите содержание для публикации', publicationContent.textContent.trim())
        let image = confirm('Изменить изображение?');

        if (image) {
            //Creating an input to select a file
            const input = document.createElement('input');

            //Configuring input
            input.type = 'file'
            input.id = 'image'
            input.accept = '.jpg,.jpeg,.png,.gif'
            input.name = 'publications[]'
            input.style.display = 'none'
            document.body.appendChild(input);

            input.addEventListener('change', function () {
                //If the image is uploaded
                send(publicationId, title, content, input.files, publicationTitle, publicationContent, publicationImage)
                document.body.removeChild(input);

            })
            //Click simulation
            input.click();
        } else {
            //If the image is not uploaded
            send(publicationId, title, content, null, publicationTitle, publicationContent, null)
        }
    }
}

/**
 * Sends the updated publication data to the server
 * 
 * @param {int} publicationId - Publication ID
 * @param {string} title - Title
 * @param {string} content - Content
 * @param {FileList|null} files - List of files to upload
 * @param {HTMLElement} publicationTitle - DOM element of the title
 * @param {HTMLElement} publicationContent - DOM element of the content
 * @param {HTMLElement|null} publicationImage - DOM-element of the image
 */
function send(publicationId, title, content, files, publicationTitle, publicationContent, publicationImage) {

    //The FormData object for sending form data
    const formData = new FormData();

    //Adding the publication data to FormData
    formData.append('identifier', publicationId);
    formData.append('title', title);
    formData.append('content', content);

    // If there are files to upload, add them to FormData
    if (files != null) {
        for (let file of files) {
            formData.append('publications[]', file)
        }
    }

    fetch('/publications/update/' + publicationId,
        {
            method: 'POST',
            body: formData
        })
        .then((response) => response.text())
        .then((text) => {

            // Updating publication data in DOM
            publicationTitle.textContent = title;
            publicationContent.textContent = content;
            publicationImage.src = "storage/publication/" + publicationId;

        })
        .catch((error) => {
            console.error('Error:', error);
        });
}