# OsUsersView.java

    /*
    ** Module   : OsUsersView.java
    ** Abstract : OsUsersView is a view to manage OS user accounts.
    **
    ** Copyright (c) 2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description----------------------
    ** 001 GBB 20230807 Created initial version.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */
    package com.goldencode.p2j.admin.client.application.home.accounts.osusers;

    import com.google.gwt.user.client.ui.*;

    import org.gwtbootstrap3.client.ui.Button;
    import org.gwtbootstrap3.client.ui.gwt.DataGrid;

    import com.goldencode.p2j.admin.TaggedName;
    import com.goldencode.p2j.admin.client.NameTokens;
    import com.goldencode.p2j.admin.client.application.home.BaseViewWithUiHandlers;
    import com.goldencode.p2j.admin.client.widget.GridHandle;
    import com.goldencode.p2j.admin.client.widget.GridHelper;
    import com.goldencode.p2j.admin.shared.PaperFormat;
    import com.goldencode.p2j.admin.shared.PaperOrientation;
    import com.goldencode.p2j.admin.shared.ReportParameters;
    import com.goldencode.p2j.admin.shared.Reports;
    import com.google.gwt.core.client.Scheduler;
    import com.google.gwt.core.client.Scheduler.ScheduledCommand;
    import com.google.gwt.dom.client.Style.Unit;
    import com.google.gwt.event.dom.client.ClickEvent;
    import com.google.gwt.uibinder.client.UiBinder;
    import com.google.gwt.uibinder.client.UiField;
    import com.google.gwt.uibinder.client.UiHandler;
    import com.google.gwt.view.client.ListDataProvider;
    import com.google.gwt.view.client.MultiSelectionModel;
    import com.google.gwt.view.client.SelectionChangeEvent;
    import com.google.inject.Inject;

    import java.util.*;
    import java.util.function.*;

    /**
     * UsersView is a view to manage user accounts.
     */
    public class OsUsersView
    extends BaseViewWithUiHandlers<OsUsersUIHandlers>
    implements OsUsersPresenter.MyView
    {
       /**
        * GWT UI creator.
        */
       interface Binder
       extends UiBinder<Widget, OsUsersView>
       {}

       /** The Refresh button */
       @UiField
       Button refresh;

       /** The Add User button */
       @UiField
       Button addOsUserAccount;

       /** The Delete User button */
       @UiField
       Button deleteOsUserAccount;

       /** The Edit User button */
       @UiField
       Button editOsUserAccount;

       /** The Disable/Enable User button */
       @UiField
       Button disableOsUserAccount;

       /** The Find User button */
       @UiField
       Button findOsUser;

       /** The all users table view */
       @UiField(provided = true)
       DataGrid<TaggedName> usersGrid = GridHelper.create();

       /** The associated FWD users table view */
       @UiField(provided = true)
       DataGrid<TaggedName> fwdUsersGrid = GridHelper.create();

       /** The modal container */
       @UiField
       HasWidgets modalFragment;

       /** The parent container for the Add/Edit User Definition view */
       @UiField
       FlowPanel osUserDefModal;

       /** The column names for the all OS users table. */
       private final String[] usersColumnNames = { "OS User ID", "Description", "Password" };

       /** The column names for the FWD users table */
       private final String[] fwdUsersColumnNames = { "FWD User" };

       /** The all OS users data provider */
       private final ListDataProvider<TaggedName> usersProvider;

       /** The FWD users data provider */
       private final ListDataProvider<TaggedName> fwdUsersProvider;

       /** The FWD users grid handle */
       private final GridHandle<TaggedName> fwdUsersGridHandle;

       /** The all OS users selection model */
       private final MultiSelectionModel<TaggedName> usersSelectionModel;

       /** The FWD users selection model */
       private final MultiSelectionModel<TaggedName> fwdUsersSelectionModel;

       /** The delete OS users view */
       private final DeletingOsUsersAlert deletingUsersAlert;

       /**
        * Constructs this view, used by MPV gwtplatform of ArcBees Inc.
        *
        * @param    binder
        *           UI creator
        * @param    deletingUsersAlert
        *           Deleting user alert child view
        */
       @Inject
       public OsUsersView(Binder binder, DeletingOsUsersAlert deletingUsersAlert)
       {
          initWidget(binder.createAndBindUi(this));

          this.deletingUsersAlert = deletingUsersAlert;

          GridHandle<TaggedName> usersGridHandle = initTable(usersGrid, usersColumnNames);
          this.usersProvider = usersGridHandle.getDataProvider();
          this.usersSelectionModel = (MultiSelectionModel<TaggedName>) usersGridHandle.getSelectionModel();
          this.usersSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
          {
             @Override
             public void onSelectionChange(SelectionChangeEvent event)
             {
                Set<TaggedName> selected = OsUsersView.this.usersSelectionModel.getSelectedSet();
                OsUsersView.this.getUiHandlers().onUserSelected(selected);
             }
          });

          usersGrid.setMinimumTableWidth(300, Unit.PX);
          setupModalSlot(OsUsersPresenter.MODAL_CONTENT, modalFragment);
          addDialog(deletingUsersAlert);

          this.fwdUsersGridHandle = initFwdUsersTable(fwdUsersGrid, fwdUsersColumnNames);
          this.fwdUsersProvider = this.fwdUsersGridHandle.getDataProvider();
          this.fwdUsersSelectionModel = (MultiSelectionModel<TaggedName>)this.fwdUsersGridHandle.getSelectionModel();
       }

       /**
        * Setups the given table view.
        *
        * @param    grid
        *           The given table view
        * @param    columnNames
        *           The column names
        *
        * @return   The grid handle
        */
       private GridHandle<TaggedName> initTable(DataGrid<TaggedName> grid, String[] columnNames)
       {
          BiFunction<TaggedName, TaggedName, Integer> comparator =
             (tn1, tn2) -> tn1.getTag().compareTo(tn2.getTag());

          GridHelper.ColumnInfo<TaggedName> col1 = new GridHelper.ColumnInfo<>(columnNames[0],
                                                                               TaggedName::getName,
                                                                               comparator);
          GridHelper.ColumnInfo<TaggedName> col2 = new GridHelper.ColumnInfo<>(columnNames[1],
                                                                               TaggedName::getTag,
                                                                               comparator);
          GridHelper.ColumnInfo<TaggedName> col3 = new GridHelper.ColumnInfo<>(columnNames[2],
                                                                               taggedName -> taggedName.get(2),
                                                                               comparator);

          return GridHelper.initListGrid(grid, true, true, col1, col2, col3);
       }

       /**
        * Setups the given table view.
        *
        * @param    grid
        *           The given table view
        * @param    columnNames
        *           The column names
        *
        * @return   The grid handle
        */
       private GridHandle<TaggedName> initFwdUsersTable(DataGrid<TaggedName> grid, String[] columnNames)
       {
          BiFunction<TaggedName, TaggedName, Integer> comparator =
             (tn1, tn2) -> tn1.getName().compareTo(tn2.getName());

          GridHelper.ColumnInfo<TaggedName> col1 = new GridHelper.ColumnInfo<>(columnNames[0],
                                                                               TaggedName::getName,
                                                                               comparator);

          return GridHelper.initListGrid(grid, true, true, col1);
       }

       /**
        * Sets the all users table's model with users accounts data given by tagged names
        *
        * @param    users
        *           The array of users accounts given by tagged names
        */
       @Override
       public void setUsers(TaggedName[] users)
       {
          logger.info("setOsUsers " + users);
          usersSelectionModel.clear();
          GridHelper.updateDataProvider(usersGrid, usersProvider, users);
       }

       /**
        * The Refresh button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("refresh")
       void onRefresh(ClickEvent e)
       {
          getUiHandlers().onRefresh();
       }

       /**
        * The Add User button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("addOsUserAccount")
       void onAddUserAccount(ClickEvent e)
       {
          logger.info("onAddOsUserAccount");
          getUiHandlers().showAddUserAccountDialog();
       }

       /**
        * The Edit User button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("editOsUserAccount")
       void onEditUserAccount(ClickEvent e)
       {
          logger.info("onEditOsUserAccount");
          TaggedName[] users = this.usersSelectionModel.getSelectedSet().toArray(new TaggedName[0]);
          getUiHandlers().showEditUserAccountDialog(users[0]);
       }

       /**
        * The Delete User button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("deleteOsUserAccount")
       void onDeleteUserAccount(ClickEvent e)
       {
          logger.info("onDeleteOsUserAccount");
          TaggedName[] users = this.usersSelectionModel.getSelectedSet().toArray(new TaggedName[0]);
          getUiHandlers().setupDeletingUsersAlert(users);
       }

       /**
        * The Find User button click handler.
        *
        * @param    e
        *           Click event
        */
       @UiHandler("findOsUser")
       void onFindUserAccount(ClickEvent e)
       {
          logger.info("onFindOsUserAccount");

          getUiHandlers().setupFindUserAccountDialog();
       }

       /**
        * Gets a reference to the Deleting Users Alert.
        *
        * @return   The Deleting Users Alert
        */
       @Override
       public DeletingOsUsersAlert getDeletingUsersAlert()
       {
          return deletingUsersAlert;
       }

       /**
        * Provides all components that must be managed by its view state machine.
        *
        * @return   The array of components managed by its view state machine
        */
       @Override
       public HasEnabled[] get()
       {
          return new HasEnabled[] {
             refresh,
             addOsUserAccount,
             deleteOsUserAccount,
             editOsUserAccount,
             disableOsUserAccount,
             findOsUser
          };
       }

       /**
        * Tests if these tested users have been selected from the all users table.
        *
        * @param    users
        *           The array of tested user accounts given by tagged names
        *
        * @return   True if all tested users have been selected, otherwise false.
        */
       @Override
       public boolean isSelectedFromUsers(TaggedName[] users)
       {
          return usersSelectionModel.getSelectedSet().containsAll(Arrays.asList(users));
       }

       /**
        * Returns the parent container where the Add/Edit OS User Definition View will be revealed in.
        *
        * @return   The parent container for the Add/Edit OS User Definition View.
        */
       @Override
       public HasWidgets getOsUserDefModalParent()
       {
          return osUserDefModal;
       }

       /**
        * Sets the FWD users table's model with all associated FWD users for the single selected OS user
        * from the OS users table view.
        *
        * @param    fwdUsers
        *           The array of FWD users given by tagged names
        */
       @Override
       public void setAssociatedFwdUsers(TaggedName[] fwdUsers)
       {
          logger.info("setAssociatedFwdUsers");
          this.fwdUsersSelectionModel.clear();
          GridHelper.updateDataProvider(fwdUsersGrid, fwdUsersProvider, fwdUsers);
       }

       /**
        * Selects the user's data row from the all users table by a given user's tagged name.
        *
        * @param    user
        *           The OS user account given by its tagged name
        */
       @Override
       public void selectUser(TaggedName user)
       {
          logger.info("selectUser " + user.getName());
          usersSelectionModel.clear();
          Scheduler.get().scheduleDeferred(() ->
                                           {
                                              usersSelectionModel.setSelected(user, true);
                                              scrollIntoView(user);
                                           });
       }

       /**
        * Sets the row with the given user within the current view.
        *
        * @param    user
        *           The user account given by its tagged name
        */
       private void scrollIntoView(TaggedName user)
       {
          int index = usersProvider.getList().indexOf(user);
          if (index >= 0)
          {
             usersGrid.getRowElement(index).scrollIntoView();
          }
       }

       /**
        * Selects the user's data row from the all users table by a given user's account name.
        *
        * @param    name
        *           The account name.
        */
       @Override
       public void selectUserByName(String name)
       {
          logger.info("setSelectedUser " + name);
          usersSelectionModel.clear();
          usersProvider.getList().forEach(user -> {
             if (user.getName().equals(name))
             {
                Scheduler.get().scheduleDeferred(new ScheduledCommand()
                {
                   @Override
                   public void execute()
                   {
                      usersSelectionModel.setSelected(user, true);
                      scrollIntoView(user);
                   }
                });
             }
          });
       }

       /**
        * Toggles the Disable/Enable User button's label.
        *
        * @param    enabled
        *           Indicates the user's enabled state. The true value switches this button's label
        *           from "Enable User" to "Disable User" and vice versa the false value switches
        *           from "Disable User" to "Enable User".
        */
       @Override
       public void toggleDisableUserButton(boolean enabled)
       {
          if (enabled)
          {
             disableOsUserAccount.setText("Disable User");
          }
          else
          {
             disableOsUserAccount.setText("Enable User");
          }
       }

       @UiHandler("disableOsUserAccount")
       public void onDisableUserAccount(ClickEvent e)
       {
          TaggedName user = usersSelectionModel.getSelectedSet().toArray(new TaggedName[0])[0];
          getUiHandlers().disableUserAccount(user);
       }

       /**
        * Returns pairs of a report parameter key and its value
        *
        * @return   The enumeration map of report parameters keys to their values
        */
       @Override
       public EnumMap<ReportParameters, Object> getReportParameters()
       {
          EnumMap<ReportParameters, Object> parameters = new EnumMap<>(ReportParameters.class);
          parameters.put(ReportParameters.SELECTION, usersSelectionModel.getSelectedSet()
                                                                        .toArray(new TaggedName[0]));
          parameters.put(ReportParameters.TITLE, "OsUsers");
          parameters.put(ReportParameters.REPORT_ID, Reports.USERS);
          parameters.put(ReportParameters.PAPER_FORMAT, PaperFormat.A4);
          parameters.put(ReportParameters.PAPER_ORIENT, PaperOrientation.PORTRAIT);

          return parameters;
       }

       /**
        * Returns the size of all data to preview or the size of selected data to preview
        *
        * @param    range
        *           The target range of selected data to preview
        * @return   The size of the selected data
        */
       @Override
       public int getDataSize(Range range)
       {
          if (range == Range.SELECTION)
          {
             return usersSelectionModel.getSelectedSet().size();
          }

          return usersProvider.getList().size();
       }

       /**
        * Returns the value of the preview dialog parameter.
        *
        * @param    parameter
        *           The preview dialog parameter key
        *
        * @return   The value of the preview dialog parameter
        */
       @Override
       public String getPreviewDialogParameter(PreviewDialogParameters parameter)
       {
          int selectedRecordsNumber = usersSelectionModel.getSelectedSet().size();
          int allRecordsNumber = usersProvider.getList().size();
          switch (parameter)
          {
             case HELP_TEXT:
                String hlpText;
                if (selectedRecordsNumber > 0)
                {
                   hlpText = "<h4>Please refine your request.</h4>";
                }
                else
                {
                   if (allRecordsNumber > 1)
                   {
                      hlpText = "<h4>" + allRecordsNumber + " user accounts being printed. Continue?</h4>";
                   }
                   else if (allRecordsNumber == 1)
                   {
                      hlpText = "<h4>1 user account being printed. Continue?</h4>";
                   }
                   else
                   {
                      hlpText = "<h4>There are no users to print. Continue?</h4>";
                   }
                }

                return hlpText;
             case TITLE:
                return "Printing Users";
             case RANGE_ALL_LABEL:
                if (allRecordsNumber > 2)
                {
                   return "all " + allRecordsNumber + " user accounts";
                }
                else if (allRecordsNumber == 2)
                {
                   return "both user accounts";
                }

                break;
             case RANGE_SELECTION_LABEL:
                if (selectedRecordsNumber > 1)
                {
                   return selectedRecordsNumber + " selected user accounts";
                }
                else if (selectedRecordsNumber == 1)
                {
                   return "the selected user account";
                }

                break;
          }

          return null;
       }

       /**
        * Returns url path to this view.
        *
        * @return   The url path.
        */
       @Override
       public String getPathToPrintPreviewOwner()
       {
          return NameTokens.USERS;
       }
    }