const createBtn = document.getElementById("create-button")
const tbody = document.getElementById("scrollable-table__tbody")
const nameInput = document.getElementById("name-input")
var fileType = document.getElementById("file-type")
var cases = []
var dataArray = [];
const wordMIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const excelMIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

window.addEventListener('load', async () => {
    try {
        await $.ajax({
            url: `/case/getallbyuser`,
            type: "GET",
            contentType: "json"
        }).done((result) => {
            cases = result;
            cases.forEach((caseModel) => {
                const { id, name, applicant, defendant, annotation, date, specialization } = caseModel;
                const row = tbody.insertRow();
                row.setAttribute("data-id", id);

                const cells = [name, applicant, defendant, annotation, date, specialization];
                cells.forEach((value) => {
                    const cell = row.insertCell();
                    cell.textContent = value;
                });

                row.addEventListener('click', () => addAndRemoveFromList(row));
            });
        });
    } catch (error) {
        console.error(error);
    }
})

createBtn.addEventListener('click', () => {
    let listModel = {
        "Cases": Array.from(dataArray),
        "FileType": fileType.value
    };
    $.ajax({
        url: "/home/specializationcaselist",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(listModel)
    }).done((file) => {
        let byteArray = new Uint8Array(file);
        saveFile(byteArray, fileType);
    });
})

const saveFile = async function (bytes, fileType) {
    if (window.showSaveFilePicker) {
        let type;
        if (fileType.value == "docx") {
            type = {
                description: "Microsoft Word (OpenXML)",
                accept: { [wordMIME]: [".docx"] }
            };
        } else if (fileType.value == "xlsx") {
            type = {
                description: "Microsoft Excel (OpenXML)",
                accept: { [excelMIME]: [".xlsx"] }
            };
        }
        
        const opts = {            
            suggestedName: `case-specialization-list.${fileType.value}`,
            types: [type],
        };
        const handle = await showSaveFilePicker(opts);
        const writable = await handle.createWritable();
        await writable.write(bytes);
        writable.close();
    }
}

const addAndRemoveFromList = (row) => {
    var id = parseInt(row.dataset.id);
    console.log(cases.find(x => x.id === id))
    var index = dataArray.indexOf(cases.find(x => x.id === id));
    if (index === -1) {
        dataArray.push(cases.find(x => x.id === id));
        row.classList.add("bg-info");
    } else {
        dataArray.splice(index, 1);
        row.classList.remove("bg-info");
    }
    console.log(dataArray);
}
