const createBtn = document.getElementById("create-button");
const nameInput = document.getElementById("name-input");
const applicantInput = document.getElementById("applicant-input");
const defendantInput = document.getElementById("defendant-input");
const annotationInput = document.getElementById("annotation-input");
const dateInput = document.getElementById("date-input");
const specializationSelect = document.getElementById("specialization-select");
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");

var specializations = [];

window.addEventListener("load", async () => {
    try {
        await $.ajax({
            url: `/case/getallspecializations`,
            type: "GET",
            contentType: "json"
        }).done((result) => {
            specializations = result;
            specializations.forEach((specialization) => {
                const option = document.createElement("option");
                option.value = specialization.id;
                option.innerHTML = specialization.name;
                specializationSelect.appendChild(option);
                specializationSelect.selectedIndex = -1;
            });
        });
    } catch (error) {
        console.error(error);
    }
});

const correctData = function () {

    return true;
};

const validate = function () {
    if (nameInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Название дела'";
        return false;
    }
    if (applicantInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Истец'";
        return false;
    }
    if (defendantInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Ответчик'";
        return false;
    }
    if (annotationInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Примечание'";
        return false;
    }
    if (specializationSelect.value === '') {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Выберите 'Специализацию'";
        return false;
    }
    return true;
};

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

    let caseModel = {
        "Name": nameInput.value,
        "Applicant": applicantInput.value,
        "Defendant": defendantInput.value,
        "Date": new Date(dateInput.value),
        "Annotation": annotationInput.value,
        "SpecializationId": parseInt(specializationSelect.value),
    };
    console.log(caseModel)
    $.ajax({
        url: "/case/create",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(caseModel)
    }).done(() => {
        window.location.href = "/Home/Cases";
    });
});