// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

/**
 * This presenter contains common code that could be used by multiple views
 * to get a list of other users logged into the appliance.  
 */

define(['fs/services/users/UserService',
        'hp/model/Session'],
function(service, session) { "use strict";

    var CommonUsersPresenter = (function() {

        /**
         * @constructor
         */
        function CommonUsersPresenter() {
        
            function getOtherUsersLoggedIn(loggedInUsersData) {
                var currentUser = '';
                var count = 0;
                var userSet = {};
                var otherLoggedInUsersList = [];

                if (loggedInUsersData.count > 0) {
                    currentUser = session.getUser();
                    currentUser = (currentUser != null)? currentUser.toLowerCase(): currentUser;
                    for ( var i = 0; i < loggedInUsersData.members.length; i++) {
                        var loggedInUser = loggedInUsersData.members[i].username.toLowerCase();
                        // creating a set to avoid duplicate elements.
                        if (!userSet[loggedInUser]) {
                            userSet[loggedInUser] = true;
                            if (loggedInUser !== currentUser) {
                                otherLoggedInUsersList[count] = loggedInUser;
                                count++;
                            }
                        }
                    }
                }
                
                return otherLoggedInUsersList;
            }
        
            /**
             * Get list of other users logged in
             *
             * @param {{success:function(OtherUsersLoggedInList):void, error:function(ErrorMessage):void}
             *     handlers Handler functions for success and error conditions.
             */
            this.getOtherUsersLoggedIn = function(handlers) {
                service.usersLoggedIn({
                    success : function(loggedInUsersData) {
                        var otherUsers = getOtherUsersLoggedIn(loggedInUsersData);
                        handlers.success(otherUsers);
                    },
                    error : function(errorInfo) {
                        handlers.error(errorInfo);
                    }
                });
            };
            
            this.init = function() {
                // nothing
            };

        }

        return new CommonUsersPresenter();
    }());

    return CommonUsersPresenter;
});
