// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/presenter/users/UsersPresenter',
        'hp/core/UrlFragment',
        'hp/core/Notifications',
        'hp/core/Localizer',
        'hp/model/Session',
        'fs/view/users/UsersViewUtil',
        'hp/view/DialogView',
        'hp/core/Router',
        'text!fsPages/users/remove_confirm.html',
        'text!fsPages/users/not_authorized.html',
        'hp/view/DetailsShowView',
        'jquery',
        'hp/lib/jquery.hpPanels',
        'hp/lib/jquery.hpDropMenu' ],
function(presenter, urlFragment, notifications, Localizer, session, UsersViewUtil,
        DialogView, router, removeConfirmHtml, notAuthorizedHtml, DetailsShowView) { "use strict";

    var UsersShowView = (function() {

        var TITLE_ROOT = '#cic-user-show .cic-details-title',
            TITLE = '#cic-user-details-title',
            PANELS = "#cic-user-panels",
            ACTIONS = '.hp-details-actions',
            ERROR = '#cic-user-details-error',
            NOTIFY_BOX = '#cic-user-show-details-notify',
            NOTIFY_MSG = "#cic-user-show-details-notify-message",
            NOTIFY_CLASS = 'hp-details-notify',
            DISMISS = '#cic-network-show-details-notify-dismiss_link',
            HELP = '#cic-user-show-details-notify-help_link',
            FORM = '#cic-user-show-form',
            NAME = '#cic-user-name',
            FULLNAME = '#cic-user-fullname',
            EMAIL = '#cic-user-email',
            OFFICE_PHONE = '#cic-user-officephone',
            MOBILE_PHONE = '#cic-user-mobilephone',
            ROLE_TYPE = '#cic-user-roletype',
            ADD_USER_LINK = '#cic-user-add-link',
            EDIT_USER_LINK='#cic-user-edit-link',
            REMOVE_ACTION = '#cic-user-remove-action',
            REMOVE_TITLE = '#cic-user-remove-confirm-title',
            UNAUTHORIZED_MSG_HEADER = '#fs-user-unauthorized-msg-header',
            USER_DETAILS_SHOW = "#user-details-show",
            USER_GROUP_DETAILS_SHOW = "#user-group-details-show",
            USER_GROUP_NAME = '#cic-user-group-name',
            DIRECTORY_TYPE = '#cic-user-group-directory-type',
            DIRECTORY_NAME = '#cic-user-group-directory-name',
            USER_GROUP_ROLE = '#cic-user-group-roletype',
            ADD_ACTIVE_DIRECTORY_ACTION_ITEM = "#cic-user-add-activedirectorylink",
            UNAUTHORIZED_MSG = '#fs-user-unauthorized-msg',
            LOGIN_DOMAINS = 'logindomains';
            var directoryGroupName;
        /**
         * Constructor
         */
        function UsersShowView() {
            var removeInProgress = false;
            var taskName;
            var detailsShowView = new DetailsShowView();
            var usersOrDirectory;
            /**
             * @private
             * update the notification banner
             */
            function updateNotify(msg, type, removable, help) {
                if (msg) {
                    $(NOTIFY_BOX).attr(
                            'class',
                            NOTIFY_CLASS + ' ' + NOTIFY_CLASS + '-' + type);
                    $(NOTIFY_MSG).html(msg);
                    if (removable) {
                        $(DISMISS).show();
                    } else {
                        $(DISMISS).hide();
                    }
                    if (help) {
                        $(HELP).show();
                    } else {
                        $(HELP).hide();
                    }
                    $(NOTIFY_BOX).slideDown('slow');
                } else {
                    $(NOTIFY_BOX).slideUp('fast');
                }
            }

            /**
             * @private
             */
            function getNotSetStyleIfEmpty(data) {
                var notSet = Localizer.getString('fs.users.show.unset');
                return (data == "") ? '<span class="hp-unset">' + notSet + '</span>' : data;
            }

            /**
             * @private
             */
            function userRoleChanged(roleList) {
                var roles = (roleList.hasOwnProperty('members') ? roleList.members : roleList);

                $(ROLE_TYPE).html($(roles).map(function() {
                    var role = this;
                    var roleValue =  role.roleName ? role.roleName.replace(/_/, ' ') : 'noname';
                    var roleDisplay = UsersViewUtil.getLocalizedRoleDisplay(roleValue);
                    return roleDisplay;
                }).get().join("<br>") );

            }

            /**
             * @private
             */
            function userRolesError(errorMessage) {
                var roleErrorMsg = Localizer.getString('fs.users.show.roleserror');

                var alertMsg = Localizer.formatRestError(roleErrorMsg, errorMessage);
                updateNotify(alertMsg, 'error', true, "#");
                $(FORM).fadeOut();
            }

            /**
             * @private
             */
            function userChanged(userObj) {
                $(USER_GROUP_DETAILS_SHOW).hide();
                $(USER_DETAILS_SHOW).show();
                urlFragment.replaceHrefUris(TITLE_ROOT, presenter.getSelection().uris);
                $(ERROR).hide();
                $(FORM).show();
                $(TITLE).html(userObj.userName);
                $(NAME).html(userObj.userName);
                $(FULLNAME).html(userObj.fullName);
                $(EMAIL).html(getNotSetStyleIfEmpty(userObj.emailAddress));
                $(OFFICE_PHONE).html(getNotSetStyleIfEmpty(userObj.officePhone));
                $(MOBILE_PHONE).html(getNotSetStyleIfEmpty(userObj.mobilePhone));
                $(ROLE_TYPE).html(userObj.roleType);

           }

            /**
            * @private
            * To show the group details
            */
           function  groupChanged(groupInfo) {
               $(USER_DETAILS_SHOW).hide();
               $(USER_GROUP_DETAILS_SHOW).show();
               urlFragment.replaceHrefUris(TITLE_ROOT, presenter.getSelection().uris);
               directoryGroupName = groupInfo.egroup;
               $(TITLE).html(groupInfo.egroup);
               $(USER_GROUP_NAME).html(groupInfo.egroup);
               $(DIRECTORY_TYPE).html(groupInfo.directoryType);
               $(DIRECTORY_NAME).html(groupInfo.loginDomain);
               $(USER_GROUP_ROLE).html(groupInfo.roles);
               }
             /**
             * @private to update show page if self details are being displayed there
             */
            function userSelfChanged(userObj){
                if(presenter.getSelectedUser().userName.toLowerCase() === session.getUser().toLowerCase()){
                    userChanged(userObj);
                }
            }

            /**
             * @private
             */
            function userError(errorMessage) {
                var userShowErrorMsg = Localizer.getString('fs.users.show.error');

                var alertMsg = Localizer.formatRestError(userShowErrorMsg,
                        errorMessage);
                updateNotify(alertMsg, 'error', true, "#");
                $(FORM).fadeOut();
            }

            function onUserDeleteSuccess(item_name) {
                var name =  presenter.getSelectedUser().userName;
                var message = Localizer.getString('fs.users.remove.success', [name]);
                presenter.updateIndexResults();
                window.location = '#/user/show';
                var successUserRemove = {
                    summary : Localizer.getString('fs.users.remove.remove') ,
                    sourceName : name,
                    uri : taskName,
                    changing : false,
                    status : "ok",
                    details : message
                };
                notifications.add(successUserRemove, true);
                removeInProgress = false;
            }

            function onUserDeleteError(errorMessage) {
                var name = presenter.getSelectedUser().userName;
                var addMsg = Localizer.getString('fs.users.remove.fail', [name]);
                var alertMsg = Localizer.formatRestError(addMsg, errorMessage);
                updateNotify(alertMsg, 'error', true, "#");
                var failureUserRemove = {
                    summary : Localizer.getString('fs.users.remove.remove') ,
                    sourceName : name,
                    sourceUri : "/rest/users/"+name,
                    uri : taskName,
                    changing : false,
                    status : "error",
                    details : alertMsg
                };
                notifications.add(failureUserRemove, true);
                removeInProgress = false;
            }
            function onGroupDeleteSuccess(item_name) {
                var successMesg = Localizer.getString('fs.users.userGroup.remove_success', [directoryGroupName]);
                presenter.updateIndexResults();
                window.location = '#/user/show';
                var successGroupRemove = {
                    summary : Localizer.getString('fs.users.remove.remove'),
                    sourceName : directoryGroupName,
                    uri : taskName,
                    changing : false,
                    status : "ok",
                    details : successMesg
                };
                notifications.add(successGroupRemove, true);
                removeInProgress = false;
            }

            function onGroupDeleteError(errorMessage) {
                var removeGroupFailMsg = Localizer.getString('fs.users.userGroup.remove_error', [directoryGroupName]);
                var alertGrpMsg = Localizer.formatRestError(removeGroupFailMsg, errorMessage);
                updateNotify(alertGrpMsg, 'error', true, "#");
                var failureGroupRemove = {
                    summary : Localizer.getString('fs.users.remove.remove'),
                    sourceName : directoryGroupName,
                    uri : taskName,
                    changing : false,
                    status : "error",
                    details : removeGroupFailMsg + '\n' + alertGrpMsg
                };
                notifications.add(failureGroupRemove, true);
                removeInProgress = false;
            }
            function onActiveDirectoryConfiguredSuccess(data) {
                if (data) {
                    $(ADD_USER_LINK).html('<a>'+Localizer.getString('fs.users.add.localuser')+'<\a>');
                    $(ADD_ACTIVE_DIRECTORY_ACTION_ITEM).show();
                } else {
                    $(ADD_USER_LINK).html('<a>'+Localizer.getString('fs.users.add.link')+'<\a>');
                    $(ADD_ACTIVE_DIRECTORY_ACTION_ITEM).hide();
                }
            }

            function onActiveDirectoryConfiguredFailure(error) {
                $(ADD_USER_LINK).html('<a>'+Localizer.getString('fs.users.add.link')+'<\a>');
                $(ADD_ACTIVE_DIRECTORY_ACTION_ITEM).hide();
            }

            function loadActionMenuItems() {
                presenter.isActiveDirectoryConfigured();
            }

            /**
             * @public
             * To remove a user
             */
            this.onRemoveItem = function() {
                if (! removeInProgress) {
                    removeInProgress = true;

                    var contents = $(removeConfirmHtml);
                    Localizer.localizeDom(contents);

                    var loginName = presenter.getSelectedUser().userName;

                    $(REMOVE_TITLE, contents).text(
                        Localizer.getString('fs.users.remove.title', [loginName]));
                    var removingMsg = Localizer.getString('fs.users.remove.removingMsg', [loginName]);

                    var dialogView = null;
                    dialogView = new DialogView({contents: contents,
                        ok: function () {
                            taskName = loginName + "-removeUserTask-" + (new Date()).getTime();
                            var beginUserRemove = {
                                summary : Localizer.getString('fs.users.remove.remove') ,
                                sourceName : loginName,
                                uri : taskName,
                                changing : true,
                                status : "info",
                                details : removingMsg
                            };
                            notifications.add(beginUserRemove, false);
                            presenter.deleteUser(presenter.getSelectedUser().userName);
                        },
                        cancel: function () {
                            removeInProgress = false;
                        }
                    });
                }
            };

            /**
             * @public
             * To remove a user
             */
            this.onRemoveDirectoryGroup = function() {
                if (! removeInProgress) {
                    removeInProgress = true;
                    var contents = $(removeConfirmHtml);
                    Localizer.localizeDom(contents);
					/*
					 * TODO: Escaping this '&' encoding, need to
					 * see if there is a better approach.
					 */
                    directoryGroupName = directoryGroupName.replace(/&amp;/g, '&');
                    $(REMOVE_TITLE, contents).text(
                        Localizer.getString('fs.users.remove.title', [directoryGroupName]));
                    var removingMsg = Localizer.getString('fs.users.remove.removingMsg', [directoryGroupName]);
                    var dialogView = null;
                    dialogView = new DialogView({contents: contents,
                        ok: function () {
                            taskName = directoryGroupName + "-removeUserTask-" + (new Date()).getTime();
                            var beginDirectoryGroupRemove = {
                                summary : Localizer.getString('fs.users.remove.remove') ,
                                sourceName : directoryGroupName,
                                uri : taskName,
                                changing : true,
                                status : "info",
                                details : removingMsg
                            };

                            notifications.add(beginDirectoryGroupRemove, false);
                            presenter.deleteDirectoryGroup(presenter.getSelection().uris[0]);
                        },
                        cancel: function () {
                            removeInProgress = false;
                        }
                    });
                }
            };

            function registerEvents() {
                presenter.on("userRoleChanged", userRoleChanged);
                presenter.on("userRolesError", userRolesError);
                presenter.on("userChangedSuccess", userChanged);
                presenter.on("userSelfChangedSuccess", userSelfChanged);
                presenter.on("userRolesError", userError);
                presenter.on("userDeleteSuccess",onUserDeleteSuccess);
                presenter.on("userDeleteError", onUserDeleteError);
                presenter.on("groupDeleteSuccess",onGroupDeleteSuccess);
                presenter.on("groupDeleteError", onGroupDeleteError);
                presenter.on("groupChangedSuccess", groupChanged);
                presenter.on("activeDirectoryConfiguredSuccess", onActiveDirectoryConfiguredSuccess);
                presenter.on("activeDirectoryConfiguredFailure", onActiveDirectoryConfiguredFailure);
            }

            function removeEvents() {
                presenter.off("userRoleChanged", userRoleChanged);
                presenter.off("userRolesError", userRolesError);
                presenter.off("userChangedSuccess", userChanged);
                presenter.off("userSelfChangedSuccess", userSelfChanged);
                presenter.off("userRolesError", userError);
                presenter.off("userDeleteSuccess",onUserDeleteSuccess);
                presenter.off("userDeleteError", onUserDeleteError);
                presenter.off("groupDeleteSuccess",onGroupDeleteSuccess);
                presenter.off("groupDeleteError", onGroupDeleteError);
                presenter.off("groupChangedSuccess", groupChanged);
                presenter.off("activeDirectoryConfiguredSuccess", onActiveDirectoryConfiguredSuccess);
                presenter.off("activeDirectoryConfiguredFailure", onUserDeleteError);
            }

            function displayErrorDialog(action, userName){

                var dialogView = null;
                dialogView = new DialogView({
                    contents : notAuthorizedHtml,
                    ok       : function(){
                                   return true;
                               }
                });
                if (action){
                    if (action === "Delete"){
                        if(session.getUser().toLowerCase() === userName.toLowerCase()){
                          $(UNAUTHORIZED_MSG_HEADER).text(Localizer.getString('fs.users.remove.title', [userName]));
                          $(UNAUTHORIZED_MSG).text(Localizer.getString('fs.users.common.self_not_authorized', [userName]));
                        }
                        else{
                          $(UNAUTHORIZED_MSG_HEADER).text(Localizer.getString('fs.users.remove.title', [userName]));
                        }
                    }
                    else if(action === "Update"){
                      $(UNAUTHORIZED_MSG_HEADER).text(Localizer.getString('fs.users.edit.link')+' '+userName);
                    }
                    else if(action === "Create"){
                      $(UNAUTHORIZED_MSG_HEADER).text(Localizer.getString('fs.users.add.title'));
                    }
                }
            }
            /**
             * @public
             * To check if user is authorized for an action
             */
            this.isUserAuthorized = function(category, action){
                var userName = presenter.getSelectedUser().userName;
                var result = false;
                if (session.canPerformAction(category,action)){
                    //self
                    if (session.getUser().toLowerCase() === userName.toLowerCase()){
                        if(action === "Delete"){
                            displayErrorDialog(action, userName);
                        }
                        else{
                            result = true;
                        }
                    }else{
                        if (userName.toLowerCase() === "administrator" && (action === "Delete" || action === "Update")){
                            displayErrorDialog(action, userName);
                        }
                        else{
                            result = true;
                        }
                    }
                }else{
                    displayErrorDialog(action, userName);
                }
                return result;
            };
            /**
             * @public
             */
            this.init = function() {
                var self = this;
                detailsShowView.init();
                $(PANELS).hpPanels();
                loadActionMenuItems();
                if(session.canManageCategory("users")){
                	$(ACTIONS).hpDropMenu();
                }else{
                	$(ACTIONS).hide();
                }
                $(DISMISS).click(function(evt) {
                    evt.preventDefault();
                    $(NOTIFY_BOX).slideUp('fast');
                });
                //because if the user cannot manage category, not authorized error
                //will be thrown by Router.js no need to show error again
                $(ADD_USER_LINK).on('click', function(ev) {
                      usersOrDirectory = presenter.getSelection().uris[0].split('/');
                      if(usersOrDirectory[2] ==='users'){
                           if (!session.canManageCategory("users")  || self.isUserAuthorized("users", "Create")){
                             router.go('/user/add','/user/show');
                             //using router.go as ev.preventDefault was giving problems
                           }
                      }else if(usersOrDirectory[2] === LOGIN_DOMAINS){
                             router.go('/user/add','/user/show');
                            //using router.go as ev.preventDefault was giving problems
                      }
                 });
                $(EDIT_USER_LINK).on('click', function(ev) {
                 usersOrDirectory = presenter.getSelection().uris[0].split('/');
                 if(usersOrDirectory[2] ==='users'){
                    var retrievedUser = presenter.getRetrievedUser().userName.toLowerCase();
                    var currentuser = session.getUser().toLowerCase();
                    var authorized = session.canPerformAction("users","Update");
                    // if user cannot update but self editing, redirect to settings edit view
                    if ((retrievedUser === currentuser) && !authorized )
                    {
                        require(['fs/view/users/UserSettingsEditView'],
                            function (view) {view.initialize();}
                        );
                    }
                    else if (!session.canManageCategory("users") || self.isUserAuthorized("users", "Update"))
                    {
                        router.go('/user/edit','/user/show');
                      } 
                    }else if(usersOrDirectory[2] === LOGIN_DOMAINS){
                        router.go('/user/group/edit','add user or group');
                    }
               });
                $(REMOVE_ACTION).on('click', function(ev) {
                    usersOrDirectory = presenter.getSelection().uris[0].split('/');
                    if(usersOrDirectory[2]==='users') {
                        if (session.canManageCategory("users")){
                            if(self.isUserAuthorized("users", "Delete")){
                                self.onRemoveItem();
                            }
                        }else{
                            router.go('/user/remove', '/user/show');//the default action is not defined in html, hence here
                        }
                    }else if (usersOrDirectory[2]=== LOGIN_DOMAINS) {
                               if (session.canManageCategory("users")){
                                    self.onRemoveDirectoryGroup();
                               }else{
                                    router.go('/user/remove', '/user/show');
                         }                 
                    }
                });
                $(ADD_ACTIVE_DIRECTORY_ACTION_ITEM).on('click', function(ev) {
                 usersOrDirectory = presenter.getSelection().uris[0].split('/');
                 if(usersOrDirectory[2]==='users') { 
                    if (!session.canManageCategory("users")  || self.isUserAuthorized("users", "Create")){
                        router.go('/user/group/add','add user or group');
                        //using router.go as ev.preventDefault was giving problems
                    }
                 }else if(usersOrDirectory[2] === LOGIN_DOMAINS){
                     router.go('/user/group/add','add user or group');
                   }
                });
                registerEvents();
                presenter.selectionChange();
                updateNotify();
            };

            /**
             * @public
             */
            this.resume = function() {
                registerEvents();
                presenter.selectionChange();
                $(PANELS).hpPanels('reset');
                removeInProgress = false;
                updateNotify();
                loadActionMenuItems();
            };

            /**
             * @public
             */
            this.pause = function() {
                removeEvents();
            };

        }

        return new UsersShowView();
    }());

    return UsersShowView;
});
