var automaticCalculation = "F";
var manualDataEntry = "V";
var numberPattern = /^-?\d+$/;

$(document).ready(function () {
    if ($("#isLicenseCM").val() === "True") { setGlobalHelpUrl($("#WorkRecordsLicenseCMHelpUrl").val()) }
    hoverYear();
    yearPicker();
    getWorkerFromUrl();
    getAutomaticCriteria();

    // initial employee selection for employee default value in create vacation modal form
    initCreateVacationModalFormEmployee();
});

function limitToIntegers(event) {
    if (!(event.charCode >= 48 && event.charCode <= 57)) {
        event.preventDefault();
    }
}

function sumManualCriteriaDays() {
    var manualCriteriaDaysSum = 0;
    $('.manual-criteria').each(function (i, obj) {
        let value = parseInt($(obj).val());
        if (!isNaN(value)) {
            manualCriteriaDaysSum += value;
        }
    });
    let sum = manualCriteriaDaysSum == 0 ? "" : manualCriteriaDaysSum;
    $("#ManualCriteriaDaysSum").val(sum);
}

function getWorkerFromUrl() {
    var url = new URL(window.location.href);
    var worker = new URLSearchParams(url.search).get('worker');
    if (worker != null) {
        openSingleVacation(worker);
    }
}

function submitVacationFilterForm() {
    $("#vacations-filter-form").submit();
}

function yearPickerChange() {
    clearButtonDisplay();
    submitVacationFilterForm();
}

function resetYearPicker() {
    $('#FilterCalculationForYear').val("").datepicker("update");
    $("#clearYearButton").attr("hidden", true);
}

function clearButtonDisplay() {
    if ($('#FilterCalculationForYear').val() != "") {
        $("#clearYearButton").removeAttr("hidden");
    }
    else {
        $("#clearYearButton").attr("hidden", true);
    }
}

function hoverYear() {
    $('.vacation-year-hover').hover(
        function () {
            $(this).find('#vacation-info-icon').removeClass('hidden');
        },

        function () {
            $(this).find('#vacation-info-icon').addClass('hidden');
        }
    );
}

function yearPicker() {
    $(".custom-yearpicker").datepicker({
        format: "yyyy",
        viewMode: "years",
        minViewMode: "years"
    });
}

function openVacationModal(id) {
    $('#' + id).modal('show');
}

function showDetailsModal(worker, year) {
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetVacationDetailsUrl").val(),
        data: {
            worker: worker,
            year: year
        },
        success: function (data) {
            if (data) {
                $('#vacation-details-modal').modal('show');
                $("#vacation-details").html(data);
                $("#vacCalcTypeDetails").selectpicker();
                $("#VacationPeriod").selectpicker();
                hideCalcCriteriaDetails();
            } else {
                showVacationErrorModal($("#VacationDoesNotExistLoc").val());
            }
        }
    });
}

function getVacationDetails(worker, year, period) {
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetVacationDetailsUrl").val(),
        data: { worker, year, period },
        success: function (data) {
            if (data) {
                $("#vacation-details").html(data);
                $("#vacCalcTypeDetails").selectpicker();
                $("#VacationPeriod").selectpicker();
                hideCalcCriteriaDetails();

                if (period) {
                    $("#VacationPeriod").val(period).selectpicker('refresh');
                }
            } else {
                $('#vacation-details-modal').modal('hide');
                showVacationErrorModal($("#VacationDoesNotExistLoc").val());
            }
        }
    });
}

function getVacationCreateData(worker, year) {
    clearVactionCreateData();
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetVacationCreateDataUrl").val(),
        contentType: "application/json",
        data: {
            worker: worker,
            year: year
        },
        success: function (data) {
            fillCreateVacationFields(data);
        }
    });
}

function clearVactionCreateData(){
    $(".cv-create-date-of-entry").val(null);
    $(".cv-create-start-absence").val(null);
    $(".cv-create-lastyr").val(null);
    $(".cv-create-ddzd").val(null);
}

function fillCreateVacationFields(data) {
    if (data.DateEnter != null) {
        $(".cv-create-date-of-entry").val(moment(data.DateEnter).format("DD.MM.YYYY"));
    }
    if (data.StartAbsence != null) {
        $(".cv-create-start-absence").val(moment(data.StartAbsence).format("DD.MM.YYYY"));
    }
    if (data.VacationLastYr != null) {
        $(".cv-create-lastyr").val(parseInt(data.VacationLastYr));
    }
    $(".cv-create-ddzd").val(data.DDZD);
}

function collapseAllVacations() {
    if ($(".collapse-all-vacations").hasClass("collapsed")) {
        $("#collapse-close").show();
        $("#collapse-open").hide();
        $(".collapse-all-vacations").removeClass('collapsed');
        $('.vacation-arrow').removeClass('collapsed');
        $('.vacations-collapse').addClass('in');
    }
    else {
        $("#collapse-close").hide();
        $("#collapse-open").show();
        $(".collapse-all-vacations").addClass('collapsed');
        $('.vacation-arrow').addClass('collapsed');
        $('.vacations-collapse').removeClass('in');
    }
}

function collapseSingleVacation(worker) {
    var worker = worker.replace(/ /g, '\\ ');
    if ($('#vacations-collapse-' + worker).hasClass('in')) {
        $('#vacations-collapse-' + worker).removeClass('in');
        $('#vacations-arrow-' + worker).addClass('collapsed');
    }
    else {
        $('#vacations-collapse-' + worker).addClass('in');
        $('#vacations-arrow-' + worker).removeClass('collapsed');
    }
}

function openSingleVacation(worker) {
    var worker = worker.replace(/ /g, '\\ ');
    let distance = 0;
    $('#vacations-collapse-' + worker).addClass('in');
    $('#vacations-arrow-' + worker).removeClass('collapsed');
    distance = isMobile() ? 460 : 200;
    $('.vacations').animate({
        scrollTop: $('#vacation-table-' + worker).offset().top - distance }, 500);
}

function changeYear(currentYear, buttonString) {
    const worker = $("#workerHidden").val();
    var yearsArray = JSON.parse($("#yearsHidden").val());
    var currentYearIndex = yearsArray.indexOf(currentYear);

    if (buttonString == 'prev' && currentYearIndex > 0) {
        currentYearIndex--;
        updateSpanYear(currentYearIndex, yearsArray);
        getVacationDetails(worker, yearsArray[currentYearIndex]);
    }

    if (buttonString == 'next' && currentYearIndex < yearsArray.length - 1) {
        currentYearIndex++;
        updateSpanYear(currentYearIndex, yearsArray);
        getVacationDetails(worker, yearsArray[currentYearIndex]);
    }
}

function updateSpanYear(index, yearsArray) {
    $('#spanYearDetails').text(yearsArray[index])
}

function changeArrowColor(currentYear) {
    var yearsArray = JSON.parse($("#yearsHidden").val());
    var currentYearIndex = yearsArray.indexOf(currentYear);

    if (currentYearIndex <= 0) {
        $("#prevYear").css("color", "darkgray");
    }

    if (currentYearIndex >= yearsArray.length - 1) {
        $("#nextYear").css("color", "darkgray");
    }
}

function calcTypeChange(calcType) {
    if (calcType.value === manualDataEntry) {
        $("#calcCriteriaList").addClass("hidden");
        $('input[name="PREFCalculationCriteria"]').closest("li").addClass("hidden");
        $("#manualCalculationPartial").removeAttr("hidden");
        $("#automaticCalculationPartial").attr("hidden", true);
        resetCalculationFields(manualDataEntry);
    }
    else {
        $("#calcCriteriaList").removeClass("hidden");
        $('input[name="PREFCalculationCriteria"]').closest("li").removeClass("hidden");
        $("#automaticCalculationPartial").removeAttr("hidden");
        $("#manualCalculationPartial").attr("hidden", true);
        resetCalculationFields(automaticCalculation);
    }
}

function employeeChange(employee) {
    var employees = $(employee).val();

    if (employees === null || employees === undefined) {
        employees = "";
    }

    var employeeValue;
    if (typeof employees === 'string') {
        employeeValue = employees;
    }
    else if (employees.length === 1) {
        employeeValue = employees[0];
    }
    if (employeeValue !== undefined && employeeValue != "") {
        $(".hide-elements-calc").removeAttr("hidden");
        $("#manualCalculationTable").removeClass("col-sm-12").addClass("col-sm-6");
        $("#manual-controls-parent").removeClass("col-sm-10").addClass("col-sm-5");
        $("#working-hours-of-day-input").removeClass("col-md-3 col-sm-3").addClass("col-md-7 col-sm-7");
        getVacationCreateData(employeeValue, $("#FilterCalculationForYearModal").val());
    }
    else {
        $(".hide-elements-calc").attr("hidden", true);
        $("#manual-controls-parent").removeClass("col-sm-5").addClass("col-sm-10");
        $("#working-hours-of-day-input").removeClass("col-md-7 col-sm-7").addClass("col-md-3 col-sm-3");
        $("#manualCalculationTable").removeClass("col-sm-6").addClass("col-sm-12");
    }
    $("#VacationLastYrCheckManual, #VacationLastYrCheckAutomatic").addClass('hidden');
}

function hideCalcCriteriaDetails() {
    if ($("#VacCalcTypeHidden").val() === manualDataEntry) {
        $("#calcCriteriaDetails").attr("hidden", true);
        $(".vac-manual-details").removeAttr("hidden");
        $(".vac-auto-details").attr("hidden", true);
    }
    else {
        $("#calcCriteriaDetails").removeAttr("hidden");
        $(".vac-manual-details").attr("hidden", true);
        $(".vac-auto-details").removeAttr("hidden");
    }
}

$(document).on('click', '.show-hide-column', function (e) {
    e.stopPropagation();
});

function showHideContent(columnName) {
    var isVisible = $("#" + columnName + "-Id").is(":checked");
    var columns = [];

    $(".show-hide-column > li > label > input").each(function () {
        var isHidden = !$(this).is(":checked");
        var columnId = $(this).attr("id");
        columnId = columnId.slice(0, -3);

        var column = {
            Id: columnId,
            IsHidden: isHidden
        };
        columns.push(column);
    });

    $.ajax({
        data:
        {
            TableName: "VacationsGrid",
            Columns: columns
        },
        type: 'POST',
        url: $("#VacationSetGridSettingsUrl").val(),
        success: function (result) {
            if (result.Status) {
                var colToHide = $(".worker-vacations-grid").find("." + columnName);
                isVisible ? colToHide.removeClass("hidden") : colToHide.addClass("hidden");
            }
        }
    });
}

function yearChange() {
    var employees = $("#FilterEmployeeModal").val()
    if (employees && employees.length === 1) {
        getVacationCreateData(employees[0], $("#FilterCalculationForYearModal").val());
    }
}

function getAutomaticCriteria() {
    $.ajax({
        type: 'GET',
        url: $("#GetAutomaticCriteriaUrl").val(),
        dataType: 'json',
        data: { criteria: $("#CalculationCriteriaModal").val() },
        success: function (data) {
            fillAutomaticCalculationTable(data);
        }
    });
}

function fillAutomaticCalculationTable(rows) {
    $("#automaticCalculationTable").find('tbody').empty();
    rows.forEach(function (criteria) {
        let newRow = $("<tr>");
        let rowText = $("<td>").text(criteria);
        newRow.append(rowText);

        $('#automaticCalculationTable tbody').append(newRow);
    });
}


function calculateVacation() {
    let inputField, errorSpan;

    if ($("#automaticCalculationPartial").is(":visible")) {
        inputField = "#VacationLastYrAutomatic";
        errorSpan = "#VacationLastYrCheckAutomatic";
    }
    if ($("#manualCalculationPartial").is(":visible")) {
        inputField = "#VacationLastYr"
        errorSpan = "#VacationLastYrCheckManual";
    }

    if (validate(inputField, errorSpan)) {
        $("#create-vacation-modal-form").submit();
    }
}

function validate(inputField, errorSpan) {
    if (!validateNumberInput($(inputField).val(), $(errorSpan))) {
        return false;
    }
    return true;
}

function validateNumberInput(inputField, errorSpan) {
    if (inputField && !numberPattern.test(inputField)) {
        errorSpan.removeClass("hidden");
        return false;
    }
    else {
        errorSpan.addClass("hidden");
        return true;
    }
}

function initCreateVacationModalFormEmployee() {
    var $employees = $('#create-vacation-modal-form select[name=Employees]');
    var $employee = $('#create-vacation-modal-form input[name=Employees]');
    if ($employees.length > 0) {
        employeeChange($employees.get(0));
    }
    else if ($employee.length > 0) {
        employeeChange($employee.get(0), true);
    }
}

function changeVacationPeriod(item) {
    var currentYear = $("#currentYearHidden").val();
    var worker = $("#workerHidden").val();
    var period = $(item).val();

    getVacationDetails(worker, currentYear, period);
}

function resetCalculationFields(calcType) {
    $("#ExtraVacation").val('');
    $(".calc-vacation-checkbox").each(function () {
        $(this).prop("checked") && $(this).trigger("click");
    });

    if (calcType === manualDataEntry) {
        disableAndEnableInputs(".automatic-input", ".manual-input");
        setDateToLastDayOfYear("#working-hours-of-day-auto");
    }
    else {
        disableAndEnableInputs(".manual-input", ".automatic-input");
        setDateToLastDayOfYear("#working-hours-of-day-manual");
    }
}

function disableAndEnableInputs(inputToDisable, inputToEnable){
    $(inputToDisable).each(function () {
        $(this).prop('disabled', true);
    });

    $(inputToEnable).each(function () {
        $(this).prop('disabled', false);
    });
}

function showVacationErrorModal(text, reload = true) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        id: "vacationErrorModal",
        type: "alert",
        text: text,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                closeOnAction: true,
                type: 'primary',
                action: function () {
                    if (reload) {
                        window.location.reload();
                    }
                }
            }
        ]
    });
}

function handleCalculateVacation(response) {
    if (response.redirectUrl) {
        window.location.href = response.redirectUrl;
    } else {
        $("#create-vacation-modal-row").addClass("hidden");
        $("#create-vacation-modal-form").append(response);
        $("#proportional-vacation-modal-row .custom-checkbox").customCheckbox();
    }
}

function continueCalculation() {
    $("#create-vacation-modal-form").submit();
}
function closeProportionalCaluclationModal() {
    $("#create-vacation-modal-row").removeClass("hidden");
    $("#proportional-vacation-modal-row").remove();
}
