'use strict';

//Hash of the last post
let lastPublications = '';

/**
 * Sends the post form data to the server and adds a new post to the page
 */
function create() {
    //FormData object for sending form data
    const formData = new FormData();

    //Form elements
    const fileInput = document.querySelector('#file-input');
    const titleInput = document.getElementById('title');
    const contentInput = document.getElementById('content');

    // Get values and trim spaces
    const title = titleInput.value.trim();
    const content = contentInput.value.trim();

    // Checking for empty fields
    if (!title) {
        alert('Заголовок не может быть пустыми!');
        return;
    }

    let hash = title + content;

    // Checking the hash of the previous publication
    if (hash === lastPublications) {

        //Form data reset
        titleInput.value = '';
        contentInput.value = '';
        fileInput.value = '';

        return;
    }

    //Getting data from FormData
    formData.append('title', titleInput.value);
    formData.append('content', contentInput.value);

    //Adding files
    if (fileInput.files.length != 0) {
        for (let i = 0; i < fileInput.files.length; i++) {
            formData.append('publications[]', fileInput.files[i]);
        }
    }

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

            //Saving the hash (success)
            lastPublications = hash;
            hash = '';

            //Clearing form fields (success)
            titleInput.value = '';
            contentInput.value = '';
            fileInput.value = '';

            //Creating an html publication
            const publication = document.createElement('div');
            const publications = document.getElementById('publications');
            publications.insertBefore(publication, publications.firstElementChild);
            publication.outerHTML = text;

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