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 lawyers = []
var dataArray = [];
const wordMIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const excelMIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

window.addEventListener('load', () => {
    $.ajax({
        url: "/lawyers/getallbyuser",
        type: "GET",
        contentType: "json"
    }).done((result) => {
        lawyers = result;
        lawyers.forEach((lawyer) => createRowForLawyersTable(lawyer));
    });
})

createBtn.addEventListener('click', () => {
    let listModel = {
        "Lawyers": Array.from(dataArray),
        "FileType": fileType.value
    };
    console.log(listModel);
    $.ajax({
        url: "/home/hearinglawyerlist",
        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: `lawyer-hearing-list.${fileType.value}`,
            types: [type],
        };
        const handle = await showSaveFilePicker(opts);
        const writable = await handle.createWritable();
        await writable.write(bytes);
        writable.close();
    }
}

const createRowForLawyersTable = (lawyer) => {
    const { id, name, surname, patronymic, experience, specialization } = lawyer;
    const row = tbody.insertRow();
    row.setAttribute("data-id", id);

    const cells = [name, surname, patronymic, experience, specialization ];
    cells.forEach((value) => {
        const cell = row.insertCell();
        cell.textContent = value;
    });

    row.addEventListener('click', () => addAndRemoveFromList(row));
};

const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
};

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