function initializeUsers() {
    let isLicenseCM = $("#isLicenseCM").val();
    var hasUserParam = url.searchParams.has('user');
    var currentUrl = new URL(window.location.href);
    currentUrl.searchParams.delete('user');
    window.history.pushState({ path: currentUrl.href }, '', currentUrl.href);

    var dtColumns = [
        {
            data: "Active", name: "AcActive",
            render: $.fn.dataTable.render.toggle(true, true),
            className: "dt-body-center"
        },
        {
            data: "Username", name: "AcUserId", filtertype: "text", render: $.fn.dataTable.render.link("Id")
        },
        { data: "Name", name: "AcName", filtertype: "text" },
        { data: "Subject", name: "AcSubject", filtertype: "text" },
    ]

    if (isLicenseCM === 'False') {
        dtColumns.push({ data: "TaxNo", name: "AcCode", filtertype: "text" });
        dtColumns.push({ data: "Granules", name: "Granules" });
    }

    $dataTable = $('#grid-data');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.Status = $("#Status").val();
                d.Granules = $("#Granules").val();
                d.LocalLicenceOnly = 'True';
            }
        },
        columns: dtColumns
    }).on('xhr.dt', function (e, settings, json, xhr) {
        if (json) {
            $('.grid-data-total-items').html(json.recordsTotal);
        }
    }).on('init.dt', function () {
        if (hasUserParam) {
            var addedUser = $dataTable.find('tbody tr').eq(0)
            addedUser.addClass('set-user-active');
            url.searchParams.delete("user");
        }
    });

    $("select").off("change.tableReload");
    $("select:not(#GranulesFilter)").on("change.tableReload", function () {
        $.fn.dataTable.reload($dataTable);
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });

    $("#GranulesFilter").on("change", function () {
        var granules = "";
        if ($("#GranulesFilter").val())
            granules = $("#GranulesFilter").val().join(",");

        $("#Granules").val(granules);
        $.fn.dataTable.reload($dataTable);
    });
}

async function updateGranules(element, url) {
    $(element).find("i").addClass("fa-spinner fa-spin");
    await fetch(url, {
        method: "POST",
        headers: { 'Content-Type': 'application/json' }
    }).then((response) => response.json()
    ).then(async (updateData) => {
        if (!updateData || updateData.success === false) throw "Error";

        $.fn.dataTable.reload($('#grid-data'));
        $(element).find("i").removeClass("fa-spinner fa-spin");
    }).catch(async (error) => {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: $("#LicenceUpgradeErrorLoc").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        $(element).find("i").removeClass("fa-spinner fa-spin");
    });
}

//Edit
function initializeUsersEdit(usernameVerification, isEdit) {
    $('.input-validation-error').parents('.form-group').addClass('has-error');
    $('.field-validation-error').addClass('text-danger');
    
    elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch-small'));
    applySwitcheryForElems(elems);
    
    elems = Array.prototype.slice.call(document.querySelectorAll('.permission'));

    applySwitcheryForElems(elems, handleUserPermissionsDisableCondition);

    elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch-parent input[type=checkbox]'));
    var switches = [];
    var counter = 0;
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
        switches[counter] = {
            value: html.value,
            switchery: switchery,
            html: html
        };
        counter++;
    });

    $('.js-switch-parent input[type=checkbox]').on('click', function () {
        if (this.checked) {
            var clickedValue = this.value;
            switches.forEach(function (switchCheckboxData) {
                if (switchCheckboxData.value !== clickedValue && switchCheckboxData.html.checked) {
                    switchCheckboxData.switchery.setPosition(true);
                }
            });
        }
        else {
            return false;
        }
    });

    initializePartnerTypeahead($("#SearchPartnersUrl").val(), $('#Subject'), $("#Subject"));

    initializeUserLicensesSelect();

    $("#saveButton").on('click', function () {
        if (!$("#Subject").val()) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: $("#subjectIsRequiredLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        } else
            $("#ContactQId").val($("#ContactPerson").val());
            $("#Contact").val($("#ContactPerson").find(':selected').text());

            var licenses = [];
            $('#SysLicencesSelect option:selected').each(function () {
                var $opt = $(this);
                licenses.push($opt.val());
            });

            $('#UserLicence').val(licenses.join(';'));

            if(isEdit){
                $('#userForm').submit();
                return;
            }

            // on create, verify username before submitting the form
            usernameVerification.verifyUsername(function() {
                $('#userForm').submit();
            }, function () {
                if (!paw.utils.value.isSet(usernameVerification.modelData.username) || usernameVerification.modelData.username.length === 0) {
                    $('#userForm').submit();
                    return;
                }
            });
    });
}

function initializeUsersCreate() {
    initializeUsersEdit();
}

function initializeChangePassword() {
    $('.input-validation-error').parents('.form-group').addClass('has-error');
    $('.field-validation-error').addClass('text-danger');
}

function openUserCreateModal() {
    let url = new URL(window.location.href);
    let worker = decodeURI(url.searchParams.get("worker"));
    if (worker !== "null") {
        $.ajax({
            cache: false,
            type: "GET",
            url: $("#CreateFromEmployeeUrl").val(),
            data: {
                worker: worker,
            },
            success: function (data) {
                openFromEmployeeModal(data);
            }
        });
    }
}

function createFromEmployee() {
    swapLoadingIcon(true, "create-from-emp-btn", "fa fa-save");
    let url = new URL(window.location.href);
    let worker = decodeURI(url.searchParams.get("worker"));
    $("#Worker").val(worker);
    $("#ContactQId").val($("#ContactPerson").val());
    $("#Contact").val($("#ContactPerson").find(':selected').text());

    $.ajax({
        url: $("#CreateFromEmployeeUrl").val(),
        type: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        enctype: 'multipart/form-data',
        data: new FormData($("#user-create-from-employee")[0]),
        success: function (data) {
            swapLoadingIcon(false, "create-from-emp-btn", "fa fa-save");

            if (data && data.userName) {
                url.searchParams.delete("worker");
                window.location.href = url.href + "?user=" + data.userName;
            }

            if (data) {
                //TODO: fix disabled after modal closing
                openFromEmployeeModal(data);
            }
        }
    });
}

function openFromEmployeeModal(data) {
    $('#create-user-modal').modal('hide');
    $("#user-create-modal").html(data);
    $('#create-user-modal').modal('show');
    userNameInitials();
    initializePartnerTypeahead($("#SearchPartnersUrl").val(), $('#Subject'), $("#Subject"));

    applySwitcheryForElems(Array.prototype.slice.call($('#create-user-modal').find('.js-switch')), handleUserPermissionsDisableCondition);
}

function userNameInitials() {
    let firstName = $("#Name").val().trim();
    let surName = $("#Surname").val().trim();
    let initials = firstName.charAt(0) + surName.charAt(0);
    $("#UserName").val(initials);
}

function getContactsBySubject(inputSubject) {
    const subject = inputSubject.value;
    const newSubjectParam = $("#ContactPerson").attr("data-url").split("=")[0] + "=" + encodeURIComponent(subject);
    $("#ContactPerson").attr("data-url", newSubjectParam);
}

function handlePermissionCheckboxes(checkbox, secondCheckbox) {
    let checkBox1 = $("#" + checkbox);
    let checkBox2 = $("#" + secondCheckbox);

    if (checkBox1.prop("checked")) {
        checkBox2.trigger('click');
    }
    if (checkBox2.prop("checked")) {
        checkBox1.trigger('click');
    }
}

function handleUserPermissionsDisableCondition(elt, switchery) {
    var $elt = $(elt);
    if (!$elt.hasClass('permission')) {
        return;
    }
    if (!$('#IsAdmin').val() || $('#IsAdmin').val().toLowerCase() !== 'true') {
        switchery.disable();
    }
}

function applySwitcheryForElems(elems, fn) {
    
    elems.forEach(function (html) {
        let switchery = new Switchery(html, { size: 'small' });
        if (fn !== undefined) {
            fn(html, switchery);
        }
    });
}

function initializeUserLicensesSelect() {
    var $sysLicensesSelect = $('#SysLicencesSelect');
    $sysLicensesSelect.attr('disabled');
    $.ajax({
        type: 'GET',
        url: $sysLicensesSelect.attr('data-url'),
        success: function (licenses) {
            var userLicenses = $('#UserLicence').val().split(';');
            var selectedLicenses = [];
            paw.utils.iterable.iterate(JSON.parse(licenses), function (licence) {
                if (userLicenses.indexOf(licence.Code) > -1) {
                    selectedLicenses.push(licence);
                    var option = new Option(licence.Name, licence.Code, true, true);
                    $sysLicensesSelect.append(option).trigger('change');
                }
            });

            $sysLicensesSelect.removeAttr('disabled');
        }
    });
}