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

            // derive from Resource
            Resource.call(this, ['users','grouptorolemappings']);

            var self = this,
                userObj,
                userRoles,
                userObjSelf,
                userRolesSelf,
                roles,
                configs;

            var otherLoggedInUsersList = [];

            function getOtherUsersLoggedIn(loggedInUsersData) {
                var userFoundLoggedIn = false;
                var currentUser = '';
                var count = 0;
                var userSet = {};

                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++;
                            }else{
                                userFoundLoggedIn = true;
                            }
                        }
                    }
                }
                return userFoundLoggedIn;
            }


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

            function onUsersLoggedInListError(errorInfo) {
                self.fire('usersLoggedInError', errorInfo);
            }

            function onGetRolesSuccess(results) {
                roles = (results && results.members) ? results.members : [];
                self.fire("rolesChanged", roles);
            }

            function onGetRolesError(errorInfo) {
                self.fire("itemError", errorInfo);
            }

            /**
             * @public
             * @return the roles defined on the appliance. If the roles haven't been retrieved yet
             *         they will be requested asynchronously and a "rolesChanged" event will be dispatched.
             */
            this.getRoles = function() {
                if (!roles) {
                    roles = [];
                    userService.getRoles({
                        success: onGetRolesSuccess,
                        error: onGetRolesError
                    });
                }
                return roles;
            };
            
            /**
             * @public
             * To get all user roles
             * @param username, handlers
             */
            this.getAllUserRoles =  function(userName,handlers) {
                var userRoleChanged = function(data) {
                    var currentUser = session.getUser();
                    currentUser = (currentUser !== null  && currentUser !== undefined)? currentUser.toLowerCase(): null;
                    userName = (userName !== null && userName !== undefined)? userName.toLowerCase(): null;
                    if(userName === currentUser){
                        userRolesSelf = data;
                    }else{
                        userRoles =  data;
                    }
                    handlers.success.call(this, data);
                };
                var userRolesError = function(errorInfo) {
                    handlers.error.call(this, errorInfo);
                };
                userService.getAllUserRoles(userName, {
                    success : userRoleChanged,
                    error : userRolesError
              });
            };


            /**
             * Get user logged in data
             * */
            this.usersLoggedIn = function(data) {
                userService.usersLoggedIn({
                    success : onUsersLoggedInListSuccess,
                    error : onUsersLoggedInListError
              });
            };

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

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

            function userDeleteSuccess(data){
                self.fire("userDeleteSuccess",data);
            }

            function userDeleteError(errorInfo){
                self.fire("userDeleteError", errorInfo);
            }
            function groupDeleteSuccess(data){
                self.fire("groupDeleteSuccess",data);
            }

            function groupDeleteError(errorInfo){
                self.fire("groupDeleteError", errorInfo);
            }
            this.deleteUser =  function(userName){
                userService.deleteUser(userName, {
                    success : userDeleteSuccess,
                    error : userDeleteError
                });
            };
            
            this.deleteDirectoryGroup =  function(uri){
                userService.deleteDirectoryGroup(uri, {
                    success : groupDeleteSuccess,
                    error : groupDeleteError
                });
            };

            this.getRetrievedRoles=function()
            {
                return userRoles;
            };

            this.getRetrievedUser=function()
            {
                return userObj ;
            };

            this.clear = function()
            {
                userObj = {};
                userRoles = {};
                userObjSelf = {};
                userRolesSelf = {};
                otherLoggedInUsersList = [];
                configs = null;
            };

            /**
             * @public
             * @param {String} username
             * Gets the user details.
             */
            this.getUser = function(userName, handlers) {
                var getUserSuccess = function(data) {
                    var currentUser = session.getUser();
                    currentUser = (currentUser != null)? currentUser.toLowerCase(): currentUser;
                    var returnedUser = (data.userName != null)? data.userName.toLowerCase(): data.userName;
                    if(returnedUser === currentUser){
                        userObjSelf = data;
                    }else{
                        userObj=data;
                    }
                    handlers.success.call(this, data);
                };
                var getUserError = function(errorInfo) {
                    handlers.error.call(this, errorInfo);
                };
                userService.getUserByName(userName, {
                    success : getUserSuccess,
                    error : getUserError}
                );
            };


            this.getRetrievedRolesSelf = function(){
                return userRolesSelf;
            };

            this.getRetrievedUserSelf = function(){
                return userObjSelf ;
            };

            /**
             * @public
             * @param {String} username .
             * Modifies the user
             */
            this.modifyUser = function(userName, handlers) {
                var modifyUserSuccess = function(data) {
                    var currentUser = session.getUser();
                    currentUser = (currentUser !== null && currentUser !== undefined)? currentUser.toLowerCase(): null;
                    var returnedUser = (data.userName !== null && data.userName !== undefined)? data.userName.toLowerCase(): null;
                    if(returnedUser === currentUser){
                        userObjSelf = data;
                    }else{
                        userObj = data;
                    }
                    handlers.success.call(this, data);
                };
                var modifyUserError = function(errorInfo) {
                    handlers.error.call(this, errorInfo);
                };
                userService.modifyUser(userName, {
                    success : modifyUserSuccess ,
                    error : modifyUserError
               });
            };

            /**
             * @private
             * Function to retrieve the values of current selection in masterpane
             * @param selection
             */
            function getSelectionValues (selection) {
             var usersorgroup = selection.uris[0].split('/');
             if(usersorgroup[2] === 'users'){
                userService.getUserByUri(selection.uris[0], {
                    success : function (data) {//if succesful get user's roles
                        userObj = data;
                        self.fire("userChangedSuccess", userObj);

                        userService.getAllUserRoles(userObj.userName, {
                            success : function (roleList){
                                userRoles = roleList;
                                self.fire("userRoleChanged",roleList);
                            },
                            error : function(errorInfo){
                                self.fire("userRolesError",errorInfo);
                            }
                        });

                    },
                    error : function (errorInfo) {
                        self.fire("userChangedError", errorInfo);
                    }}
                );
             }else if(usersorgroup[2] === 'logindomains') {
                 userService.getResource(selection.uris[0], {
                     success : function (data) {//if succesful get groups data
                         self.fire("groupChangedSuccess", data);
                      },
                     error : function (errorInfo) {
                         self.fire("groupChangedError", errorInfo);
                     }}
                 );
             }
            };

            /**
             * Listener for selectionChange event
             */
            this.on("selectionChange", function(selection) {
                if (selection.uris && selection.uris.length > 0) {
                    getSelectionValues(selection);
                }
            });


            /**
             * @public
             * Function that is public
             * @param selection
             */
            this.selectionChange = function(selection){
                if (selection.uris && selection.uris.length > 0) {
                  getSelectionValues(selection);
                }
            };


            /**
             * @public
             * This function is used to retrieve values in the /ci/etc/product-config.json file
             *
             */
            this.getProductConfig = function(handlers) {
                function onGetProductConfigSuccess(productConfigs) {
                    configs = (productConfigs) ? productConfigs : {};
                    handlers.success.call(this, configs);
                }

                function onGetProductConfigError(errorInfo) {
                    handlers.error.call(this, errorInfo);
                }
                if (!configs) {
                    configs = {};
                    userService.getProductConfig({
                        success: onGetProductConfigSuccess,
                        error: onGetProductConfigError
                    });
                }else{
                    handlers.success.call(this, configs);
                }
            };

        }
        return new UserResource();
    }());
    return UserResource;
});

