# AcquiredLocksPresenter.java

    /*
    ** Module   : AcquiredLocksPresenter.java
    ** Abstract : AcquiredLocksPresenter represents a controller to manage acquired locks.
    **
    ** Copyright (c) 2017-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 SBI 20170601 Created initial version.
    ** 002 OM  20241128 Multi-tenant runtime support: selected the proper persistence context, eventually
    **                  based on [sharedDb] parameter.
    */

    /*
    ** 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.console.acquiredlocks;

    import java.util.Arrays;
    import java.util.LinkedHashSet;
    import java.util.Set;
    import java.util.logging.Level;

    import javax.inject.Named;

    import com.goldencode.p2j.admin.RecordInfo;
    import com.goldencode.p2j.admin.client.*;
    import com.goldencode.p2j.admin.client.application.Alarm;
    import com.goldencode.p2j.admin.client.application.home.*;
    import com.goldencode.p2j.admin.client.application.home.ViewStateMachine.TransitionState;
    import com.goldencode.p2j.admin.client.widget.dialog.MessageType;
    import com.goldencode.p2j.admin.client.widget.dialog.ModalDialogs;
    import com.goldencode.p2j.admin.shared.AdminServiceAsync;
    import com.goldencode.p2j.persist.*;
    import com.google.gwt.user.client.rpc.AsyncCallback;
    import com.google.gwt.user.client.ui.HasEnabled;
    import com.google.inject.*;
    import com.google.web.bindery.event.shared.*;
    import com.gwtplatform.mvp.client.*;
    import com.gwtplatform.mvp.client.annotations.*;
    import com.gwtplatform.mvp.client.presenter.slots.*;
    import com.gwtplatform.mvp.client.proxy.*;
    import com.gwtplatform.mvp.shared.proxy.PlaceRequest;

    /**
     * Manages acquired locks.
     */
    public class AcquiredLocksPresenter
    extends PresenterWithStateMachine<AcquiredLocksPresenter.MyView, AcquiredLocksPresenter.MyProxy>
    implements AcquiredLocksUIHandler
    {
       /** Defines the view transitional state in which the acquired lock table is empty. */
       private static final boolean[] NO_RECORDS_STATE =
                new boolean[] {
                                  /*lockRecords*/      false,
                                  /*unlockRecords*/    false,
                                  /*addRecord*/        true,
                                  /*deleteSelected*/   false,
                                  /*deleteAllRecords*/ false
                               };

       /** Defines the view transitional state in which the acquired lock table has a one row at least. */
       private static final boolean[] THERE_IS_RECORD_STATE =
                new boolean[] {
                                  /*lockRecords*/      true,
                                  /*unlockRecords*/    false,
                                  /*addRecord*/        true,
                                  /*deleteSelected*/   false,
                                  /*deleteAllRecords*/ true
                               };

       /** Defines the view transitional state in which the acquired lock table has locked records. */
       private static final boolean[] THERE_IS_LOCK_STATE =
                new boolean[] {
                                  /*lockRecords*/      true,
                                  /*unlockRecords*/    true,
                                  /*addRecord*/        true,
                                  /*deleteSelected*/   false,
                                  /*deleteAllRecords*/ true
                               };

       /** Defines the view transitional state in which the acquired lock table has selected rows. */
       private static final boolean[] SELECTION_NOT_EMPTY_STATE =
                new boolean[] {
                                  /*lockRecords*/      false,
                                  /*unlockRecords*/    false,
                                  /*addRecord*/        true,
                                  /*deleteSelected*/   true,
                                  /*deleteAllRecords*/ true
                               };

       /** Defines the buttons mask in which the Lock and Unlock buttons are enabled. */
       private static final boolean[] LOCK_TABLE_BUTTONS =
                new boolean[] {
                                  /*lockRecords*/      true,
                                  /*unlockRecords*/    true,
                                  /*addRecord*/        false,
                                  /*deleteSelected*/   false,
                                  /*deleteAllRecords*/ false
                               };

       /** Defines the buttons mask in which the Delete Selected button is enabled. */
       private static final boolean[] SELECTION_BUTTONS =
                new boolean[] {
                                  /*lockRecords*/      false,
                                  /*unlockRecords*/    false,
                                  /*addRecord*/        false,
                                  /*deleteSelected*/   true,
                                  /*deleteAllRecords*/ false
                               };

       /** Defines the buttons mask in which the Lock and Delete All buttons are enabled. */
       private static final boolean[] TABLE_BUTTONS =
                new boolean[] {
                                  /*lockRecords*/      true,
                                  /*unlockRecords*/    false,
                                  /*addRecord*/        false,
                                  /*deleteSelected*/   false,
                                  /*deleteAllRecords*/ true
                               };

       /** Defines the buttons mask in which all buttons are enabled. */
       private static final boolean[] ALL_BUTTONS =
                new boolean[] {
                                  /*lockRecords*/      true,
                                  /*unlockRecords*/    true,
                                  /*addRecord*/        true,
                                  /*deleteSelected*/   true,
                                  /*deleteAllRecords*/ true
                               };

       /**
        * Defines the Acquired Locks View states
        */
       public static enum AcquiredLocksViewStates
       implements ViewStateMachine.TransitionState
       {
          /** The acquired lock table has been empty. */
          EMPTY_RECORDS(ALL_BUTTONS, NO_RECORDS_STATE),

          /** The acquired lock table has a row. */
          THERE_IS_A_RECORD(TABLE_BUTTONS, THERE_IS_RECORD_STATE),

          /** The acquired lock table has a locked record. */
          THERE_IS_A_LOCK(LOCK_TABLE_BUTTONS, THERE_IS_LOCK_STATE),

          /** The acquired lock table has an empty selection. */
          SELECTION_IS_EMPTY(SELECTION_BUTTONS, NO_RECORDS_STATE),

          /** The acquired lock table has selected rows. */
          RECORDS_SELECTED(SELECTION_BUTTONS, SELECTION_NOT_EMPTY_STATE);

          /** The current components states to be enabled or disabled */
          private final boolean[] state;

          /** The current mask that defines components to which the current state is applied */
          private final boolean[] mask;

          /**
           * Creates a target view state.
           *
           * @param    mask
           *           The current mask
           * @param    state
           *           The current state
           */
          private AcquiredLocksViewStates(boolean[] mask, boolean[] state)
          {
             this.mask  = mask;
             this.state = state;
          }

          /**
           * Gets the current state that defines the affected components states.
           *
           * @return   The current state
           */
          @Override
          public boolean[] getState()
          {
             return this.state;
          }

          /**
           * Gets the current mask that defines the set of affected components (widgets).
           *
           * @return   The current mask
           */
          @Override
          public boolean[] getMask()
          {
             return mask;
          }
       }

       /** The attachment point for modal dialogs on this view */
       public static final NestedSlot MODAL_CONTENT = new NestedSlot();

       /** Administration server interface */
       private final AdminServiceAsync adminService;

       /** The server alarms manager */
       private final Alarm serverAlarmsManager;

       /** The common modal dialogs manager */
       private final ModalDialogs modalDialogsManager;

       /**
        * All locked records
        */
       private final LinkedHashSet<RecordInfo> lockedRecords;

       /** New records added to the acquired records table but not locked yet */
       private final LinkedHashSet<RecordInfo> addedRecords;

       /**
        * This view interface that must be implemented by the concrete view according to GWTP
        * framework. Defines the exposed business methods.
        */
       public interface MyView
       extends View, HasUiHandlers<AcquiredLocksUIHandler>, Provider<HasEnabled[]>
       {
          /**
           * Sets the acquired locks table model.
           *
           * @param    locks
           *           The array of records
           */
          void setRecordLocks(RecordInfo[] locks);

          /**
           * Tests if the given record set has been selected.
           *
           * @param    records
           *           The set of tested records
           *
           * @return   True if the tested record set has been selected, otherwise false.
           */
          boolean isRecordsSelected(Set<RecordInfo> records);

          /**
           * Gets a reference to the Add Record Lock View.
           *
           * @return   The Add Record Lock View
           */
          AddRecordLockView getAddRecordLockView();
       }

       /**
        * Defines the proxy place for GWTP framework.
        */
       @ProxyStandard
       @NameToken(NameTokens.ACQUIRED_LOCKS)
       public interface MyProxy
       extends ProxyPlace<AcquiredLocksPresenter>
       {}

       /**
        * Defines the Acquired Locks presenter.
        *
        * @param    eventBus
        *           The event bus
        * @param    view
        *           The associated view
        * @param    proxy
        *           The proxy place
        * @param    placeManager
        *           The place manager
        * @param    viewStateMachine
        *           The view state machine
        * @param    adminService
        *           The administration service
        * @param    modalDialogsManager
        *           The common modal dialogs manager
        * @param    serverAlarmsManager
        *           The server alarms
        */
       @Inject
       AcquiredLocksPresenter(EventBus eventBus,
                              MyView view,
                              MyProxy proxy,
                              PlaceManager placeManager,
                              @Named("AcquiredLocksViewStateMachine")
                              ViewStateMachine viewStateMachine,
                              AdminServiceAsync adminService,
                              ModalDialogs modalDialogsManager,
                              Alarm serverAlarmsManager)
       {
          super(eventBus, view, proxy, HomePresenter.SLOT_CONTENT, placeManager, viewStateMachine);
          this.adminService  = adminService;
          this.modalDialogsManager = modalDialogsManager;
          this.serverAlarmsManager = serverAlarmsManager;
          this.lockedRecords = new LinkedHashSet<RecordInfo>();
          this.addedRecords  = new LinkedHashSet<RecordInfo>();
          getView().setUiHandlers(this);
       }

       /**
        * Loads the data before the associated view will be displayed.
        *
        * @param    request
        *           The current request
        */
       @Override
       public void prepareFromRequest(PlaceRequest request)
       {
          super.prepareFromRequest(request);
          updateLockedRecords(()->{
             if (lockedRecords.isEmpty() && addedRecords.isEmpty())
             {
                setState(AcquiredLocksViewStates.EMPTY_RECORDS);
             }
             else
             {
                setState(AcquiredLocksViewStates.THERE_IS_A_RECORD);
                if (!lockedRecords.isEmpty())
                {
                   changeState(AcquiredLocksViewStates.THERE_IS_A_LOCK);
                }
             }
          });
          refreshDatabases();
       }

       /**
        * Retrieves all managed databases asynchronously and refreshes the corresponding widgets.
        */
       public void refreshDatabases()
       {
          adminService.getDatabases(new AsyncCallback<String[]>()
          {

             @Override
             public void onFailure(Throwable caught)
             {
                logger.log(Level.SEVERE, "Failed to call getDatabases", caught);
             }

             @Override
             public void onSuccess(String[] result)
             {
                getView().getAddRecordLockView().setDatabaseList(result);
             }
          });

       }

       /**
        * Retrieves all tables from the given database asynchronously and refreshes the corresponding
        * widgets.
        *
        * @param    databaseName
        *           The given database
        */
       public void refreshTables(String databaseName)
       {
          adminService.getDatabaseTables(databaseName, new AsyncCallback<String[]>()
          {

             @Override
             public void onFailure(Throwable caught)
             {
                logger.log(Level.SEVERE, "Failed to call getDatabaseTables", caught);
             }

             @Override
             public void onSuccess(String[] result)
             {
                getView().getAddRecordLockView().setTableList(result);
             }
          });
       }

       /**
        * Executes the action to lock new added records from the acquired locks table.
        */
       @Override
       public void lockRecords()
       {
          RecordInfo[] records = addedRecords.toArray(new RecordInfo[addedRecords.size()]);

          adminService.lockRecords(records, new AsyncCallback<Boolean>()
          {

             @Override
             public void onFailure(Throwable caught)
             {
                logger.log(Level.SEVERE, "Failed to call lockRecords", caught);
                updateLockedRecords();
             }

             @Override
             public void onSuccess(Boolean result)
             {
                if (result == null || !result.booleanValue())
                {
                   serverAlarmsManager.ring();
                }
                else
                {
                   addedRecords.clear();
                }
                updateLockedRecords();
             }
          });

       }

       /**
        * Executes the action to unlock locked records.
        */
       @Override
       public void unlockRecords()
       {
          adminService.unlockRecords(new AsyncCallback<Boolean>()
          {

             @Override
             public void onFailure(Throwable caught)
             {
                logger.log(Level.SEVERE, "Failed to call unlockRecords", caught);
                updateLockedRecords();
             }

             @Override
             public void onSuccess(Boolean result)
             {
                if (result == null || !result)
                {
                   serverAlarmsManager.ring();
                }
                updateLockedRecords();
             }
          });

       }

       /**
        * Adds new unlocked record to the acquired locks table view.
        *
        * @param    databaseName
        *           The given database
        * @param    tableName
        *           The given table containing the target record
        * @param    recordID
        *           The target record identification number
        */
       @Override
       public void addRecordToLocks(String databaseName, String tableName, Long recordID)
       {
          RecordInfo rec = new RecordInfo(databaseName, tableName, recordID, Persistence.PRIVATE_CTX);
          addedRecords.add(rec);
          updateLockedRecords(() -> {
             getView().getAddRecordLockView().getModal().hide();
             if (lockedRecords.isEmpty() && addedRecords.isEmpty())
             {
                setState(AcquiredLocksViewStates.EMPTY_RECORDS);
             }
             else
             {
                changeState(AcquiredLocksViewStates.THERE_IS_A_RECORD);
                if (!lockedRecords.isEmpty())
                {
                   changeState(AcquiredLocksViewStates.THERE_IS_A_LOCK);
                }
             }
          });
       }

       /**
        * Retrieves all locked records from the server asynchronously and refreshes the acquired locks
        * table model and view if this action is completed successfully.
        */
       private void updateLockedRecords()
       {
          updateLockedRecords(() -> {
             if (lockedRecords.isEmpty() && addedRecords.isEmpty())
             {
                setState(AcquiredLocksViewStates.EMPTY_RECORDS);
             }
             else
             {
                changeState(AcquiredLocksViewStates.THERE_IS_A_RECORD);
                if (!lockedRecords.isEmpty())
                {
                   changeState(AcquiredLocksViewStates.THERE_IS_A_LOCK);
                }
             }
          });
       }

       /**
        * Retrieves all locked records from the server asynchronously and refreshes the acquired locks
        * table model and performs the ui command if this action is completed successfully.
        *
        * @param    command
        *           The ui command
        */
       private void updateLockedRecords(Runnable command)
       {
          adminService.getLockRecords(new AsyncCallback<RecordInfo[]>()
          {

             @Override
             public void onFailure(Throwable caught)
             {
                logger.log(Level.SEVERE, "Failed to call getLockRecords", caught);
             }

             @Override
             public void onSuccess(RecordInfo[] result)
             {
                LinkedHashSet<RecordInfo> locked = new LinkedHashSet<RecordInfo>(result.length);
                locked.addAll(Arrays.asList(result));
                lockedRecords.forEach(rec -> {
                   if (!locked.contains(rec))
                   {
                      addedRecords.add(rec);
                   }
                });
                lockedRecords.clear();
                lockedRecords.addAll(locked);
                LinkedHashSet<RecordInfo> data = new LinkedHashSet<RecordInfo>(lockedRecords.size()
                         + addedRecords.size());
                data.addAll(lockedRecords);
                data.addAll(addedRecords);
                getView().setRecordLocks(data.toArray(new RecordInfo[data.size()]));
                command.run();
             }
          });
       }

       /**
        * Delete the selected unlocked records. If the selected record is locked, then it cann't be
        * removed from the acquired locks table. It is required to unlock records first and then
        * delete selected records.
        *
        * @param    selected
        *           The set of selected records
        */
       @Override
       public void deleteSelectedRecords(Set<RecordInfo> selected)
       {
          if (selected == null || selected.isEmpty())
          {
             return;
          }
          if (!getView().isRecordsSelected(selected))
          {
             return;
          }
          int size = selected.size();
          String message;
          if (size > 1)
          {
             message = size + " records being deleted. Continue?";
          }
          else
          {
             message = "1 record being deleted. Continue?";
          }
          String title   = "Deleting Acquired Locks";
          modalDialogsManager.showYesNo(title, message, MessageType.QUESTION, button -> {
             if (button == 0)
             {
                addedRecords.removeAll(selected);
                lockedRecords.removeAll(selected);
                updateLockedRecords();
             }
          });
       }

       /**
        * Delete all unlocked records from the acquired locks table.
        */
       @Override
       public void deleteAllRecords()
       {
          String message = "All records being deleted. Continue?";
          String title   = "Deleting Acquired Locks";
          modalDialogsManager.showYesNo(title, message, MessageType.QUESTION, button -> {
             if (button == 0)
             {
                addedRecords.clear();
                lockedRecords.clear();
                updateLockedRecords();
             }
          });
       }

       /**
        * Applies the given transitional state to the current state of the view state machine.
        *
        * @param    transitionState
        *           The given transitional state
        */
       @Override
       public void setCurrentState(TransitionState transitionState)
       {
          changeState(transitionState);
       }
    }