// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(
    ['fs/services/users/UserService',
     'hp/model/Session',
     'hp/core/EventDispatcher',
     'jquery'],
function(userService, session, EventDispatcher) {"use strict";
    var CertificateModel = ( function() {
        function CertificateModel() {

            var dispatcher = new EventDispatcher();

            var otherLoggedInUsersList = [];

            function getOtherUsersLoggedIn(loggedInUsersData) {
                var userSet = {};
                // clear old data
                otherLoggedInUsersList = [];
                if (loggedInUsersData.count > 0) {
                    var currentUser = session.getUser();
                    for ( var i = 0; i < loggedInUsersData.members.length; i++) {
                        // TODO: change this to a scrollable list
                        var loggedInUser = loggedInUsersData.members[i].username;
                        // creating a set to avoid duplicate elements.
                        if (!userSet[loggedInUser]) {
                            userSet[loggedInUser] = true;
                            if (loggedInUser !== currentUser) {
                                otherLoggedInUsersList.push(loggedInUser);
                            }
                        }
                    }
                }
            }

            function onUsersLoggedInListSuccess(data) {
                getOtherUsersLoggedIn(data);
                dispatcher.fire('usersLoggedInSuccess', data);
            }

            function onUsersLoggedInListError(errorInfo) {
                // clear old data
                otherLoggedInUsersList = [];
                dispatcher.fire('usersLoggedInError', errorInfo);
            }

            this.usersLoggedIn = function(data) {
                userService.usersLoggedIn({
                    success : onUsersLoggedInListSuccess,
                    error : onUsersLoggedInListError
                });
            };

            this.setOtherUsersLoggedInList = function(list) {
                otherLoggedInUsersList = list;
            };

            this.getOtherUsersLoggedInList = function() {
                return otherLoggedInUsersList;
            };

            this.on = function(eventName, callback) {
                dispatcher.on(eventName, callback);
            };

            this.off = function(eventName, callback) {
                dispatcher.off(eventName, callback);
            };
        }

        return new CertificateModel();

    }());

    return CertificateModel;

});