const createBtn = document.getElementById("create-button");
const subjectInput = document.getElementById("subject-input");
const responsibilitiesInput = document.getElementById("responsibilities-input");
const dateInput = document.getElementById("date-input");
const tbody = document.getElementById("scrollable-table__tbody")
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");

var cases = [];
var dataArray = [];

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);
    }
});

const correctData = function () {

    return true;
};

const validate = function () {
    if (subjectInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Предмет договора'";
        return false;
    }
    if (responsibilitiesInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Обязаности'";
        return false;
    }
    if (dataArray.length === 0) {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните список 'Дел'";
        return false;
    }
    return true;
};

createBtn.addEventListener("click", () => {
    if (!correctData()) {
        return;
    }
    if (!validate()) {
        return;
    }

    let dealModel = {
        "Subject": subjectInput.value,
        "Responsibilities": responsibilitiesInput.value,
        "Date": new Date(dateInput.value),
        "CaseViewModels": dataArray
    };
    console.log(dealModel)
    $.ajax({
        url: "/deal/create",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(dealModel)
    }).done(() => {
        window.location.href = "/Home/Deals";
    });
});

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);
}