define(['./users_list_popup.component.html'], function (template)
{
    var UsersListPopup = {
        bindings: {},
        templateUrl: template,
        controller: [
            '$element',
            'userListService',
            function ($element, userListService) {
                var ctrl = this;

                ctrl.users = [];
                ctrl.currentPage = 1;
                ctrl.usersPerPage = 10;
                ctrl.totalItems = 0;
                ctrl.paginatedUsers = []

                ctrl.$onInit = function() {
                    $element.find('.js-users_list_modal').on('update', function(event, users) {
                        ctrl.users = users;

                        ctrl.currentPage = 1;
                        ctrl.totalItems = ctrl.users.length;
                        ctrl.pageChanged(ctrl.currentPage);
                    });
                };

                // If pagination is clicked
                ctrl.pageChanged = function(newPage)
                {
                    ctrl.paginatedUsers = paginate(ctrl.users, ctrl.usersPerPage, newPage);
                };

                function paginate(users, usersPerPage, currentPage) {
                    return users.slice((currentPage - 1) * usersPerPage, currentPage * usersPerPage);
                }
            }
        ]
    };

    return UsersListPopup;
});
