const updateBtn = document.getElementById("update-button");
const informationInput = document.getElementById("information-input");
const dateInput = document.getElementById("date-input");
const caseSelect = document.getElementById("case-select");
const hearingId = document.getElementById("vb-id").dataset.id;
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");

var cases = [];

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

window.addEventListener("load", async () => {
    try {
        await $.ajax({
            url: `/hearing/get?id=${hearingId}`,
            type: "GET",
            contentType: "json"
        }).done((result) => {
            informationInput.value = result.information;
            dateInput.value = formatDate(result.date);
        });
        await $.ajax({
            url: "/case/getallbyuser",
            type: "GET",
            contentType: "json"
        }).done((result) => {        
            cases = result;
            cases.forEach((element) => {
                const option = document.createElement("option");
                option.value = element.id;
                option.innerHTML = "Дело №" + element.id;
                caseSelect.appendChild(option);
                caseSelect.selectedIndex = -1;
            });
        });
    } catch (error) {
        console.error(error);
    }
});

const correctData = function () {

    return true;
};

const validate = function () {
    if (informationInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Информация по слушанию'";
        return false;
    }
    if (caseSelect.value === '') {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Выберите 'Дело'";
        return false;
    }
    return true;
};

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

    let hearingModel = {
        "Id": parseInt(hearingId),
        "Information": informationInput.value,
        "CaseId": parseInt(caseSelect.value),
        "Date": dateInput.value
    };
    console.log(hearingModel)
    $.ajax({
        url: "/hearing/update",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(hearingModel)
    }).done(() => {
        window.location.href = "/Home/Hearings";
    });
});