/*
 * AixFlow plugin JavaScript functions.
 */
"use strict";

// Create namespace if it doesn't exist
if (!$$.pl) $$.pl = {};
$$.pl.aixflow = {};

// Extend $$.ui.upload with filesUpload function
$$.ui.upload.filesUpload = function(form, uploadForm, files) {
    // array with uploaded files: id and title
    const uploadedFiles = [];

    const sendNextFile = (file) => {
        if (file)
            $$.ajax
                .fileSend(uploadForm, file)
                .done((response) => {
                    if (response.data && response.data.file)
                        uploadedFiles.push(response.data.file);
                })
                .always(() => sendNextFile(files.shift()));
        else
            $$.ui.upload.uploadListAdd(form, uploadedFiles);
    }

    sendNextFile(files.shift());
};

// Make uploadListAdd function public
$$.ui.upload.uploadListAdd = function(form, fileIdTitleList) {
    const uploadList = form.querySelector(".upload-list");
    fileIdTitleList.forEach((file) => {
        const deleteCode = "$$.ajax.post('/user/file.do?method=temporaryDelete&id=" + file.id + "').done(() => {$(this.parentNode).remove()})";
        $(uploadList).append(
            "<div>" +
                "<input type=\"hidden\" name=\"tmpFileId\" value=\"" + file.id + "\"/>" +
                "<button class=\"btn-white btn-small mr05 icon\" type=\"button\" onclick=\"" + deleteCode + "\"><i class=\"ti-trash\"></i></button> " + file.title +
            "</div>");
    });
};