# GridHandle.java

    /*
    ** Module   : GridHandle.java
    ** Abstract : Grid handle.
    **
    ** Copyright (c) 2017, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --------------------------------Description-----------------------------------
    ** 001 HC  20170612 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.widget;

    import com.google.common.base.Predicate;
    import com.google.common.collect.*;
    import com.google.gwt.regexp.shared.*;
    import com.google.gwt.user.cellview.client.*;
    import com.google.gwt.view.client.*;

    import java.util.*;

    /**
     * A class providing convenience methods for working with instance of
     * {@link org.gwtbootstrap3.client.ui.gwt.DataGrid}.
     */
    public class GridHandle<TRowObject>
    {
       /** The wrapped grid */
       private DataGrid grid;

       /** Data provider */
       private ListDataProvider<TRowObject> dataProvider;

       /** Selection model reference */
       private SetSelectionModel<TRowObject> selectionModel;

       /** The selected records */
       private Set<TRowObject> selected;

       /**
        * Ctor.
        *
        * @param   grid
        *          The grid instance to wrap.
        * @param   dataProvider
        *          The data provider.
        * @param   selectionModel
        *          The selection model.
        */
       public GridHandle(DataGrid grid,
                         ListDataProvider<TRowObject> dataProvider,
                         SetSelectionModel<TRowObject> selectionModel)
       {
          this.grid = grid;
          this.dataProvider = dataProvider;
          this.selectionModel = selectionModel;
       }

       /**
        * Returns the wrapped grid.
        *
        * @return  see above
        */
       public DataGrid getGrid()
       {
          return grid;
       }

       /**
        * Returns the data provider.
        *
        * @return  see above
        */
       public ListDataProvider<TRowObject> getDataProvider()
       {
          return dataProvider;
       }

       /**
        * Returns the grid selection model.
        *
        * @return  see above
        */
       public SelectionModel<TRowObject> getSelectionModel()
       {
          return selectionModel;
       }

       /**
        * Unselects the currently selected rows.
        */
       public void clearSelection()
       {
          selected = null;
          selectionModel.clear();

          // this will make the (multi) selection model to apply any pending changes right away,
          // this is needed in case when a row is about change its key (see
          // AbstractSelectionModel.getKey())
          selectionModel.getSelectedSet();
       }

       /**
        * Returns the set of selected rows.
        *
        * @return  see above
        */
       public Set<TRowObject> getSelected()
       {
          return selectionModel.getSelectedSet();
       }

       /**
        * Return the single selected row. Note that this method can be used only when the
        * selection model is of type {@link SingleSelectionModel}.
        *
        * @return  see above
        */
       public TRowObject getSelectedSingle()
       {
          if (selectionModel instanceof SingleSelectionModel)
          {
             return ((SingleSelectionModel<TRowObject>) selectionModel).getSelectedObject();
          }
          else
          {
             throw new RuntimeException("Single selection model expected!");
          }
       }

       /**
        * Select the provided row. When the row is not present in the grid this method is a no-op.
        *
        * @param   row
        *          The row to select.
        */
       public void select(TRowObject row)
       {
          selected = null;
          selectionModel.setSelected(row, true);
       }

       /**
        * Clears the grid - removes all rows and clears the selection.
        */
       public void clearGrid()
       {
          clearGrid(true);
       }

       /**
        * Clears the grid - removes all rows and clears the selection.
        *
        * @param   keepSelection
        *          This flag allows to keep the current selection.
        */
       public void clearGrid(boolean keepSelection)
       {
          if (keepSelection)
          {
             storeSelected();
          }
          else
          {
             selected = null;
          }

          Set<TRowObject> rescue = selected;
          clearSelection();
          dataProvider.getList().clear();
          dataProvider.refresh();
          selected = rescue;
       }

       /**
        * Adds rows to the grid's data provider.
        *
        * @param   rows
        *          The rows to add.
        */
       public void addRows(List<TRowObject> rows)
       {
          dataProvider.getList().addAll(rows);
          restoreSelected();
       }

       /**
        * Adds rows to the grid's data provider.
        *
        * @param   rows
        *          The rows to add.
        */
       public void addRows(TRowObject[] rows)
       {
          dataProvider.getList().addAll(Arrays.asList(rows));
          ColumnSortEvent.fire(grid, grid.getColumnSortList());
          restoreSelected();
       }

       /**
        * Adds rows to the grid's data provider. Only those rows that satisfy the supplied
        * regular expression are added, all the row columns are tested against the expression.
        *
        * @param   rows
        *          The rows to add.
        * @param   filterExp
        *          Regular expression.
        */
       public void addRows(List<TRowObject> rows, RegExp filterExp)
       {
          Predicate<TRowObject> filterRecords = record ->
          {
             if (filterExp == null)
             {
                return true;
             }

             for (int i = 0; i < grid.getColumnCount(); i++)
             {
                Column<TRowObject, ?> column = grid.getColumn(i);
                if (filterExp.test(column.getValue(record).toString()))
                {
                   return true;
                }
             }

             return false;
          };

          dataProvider.getList().addAll(Collections2.filter(rows, filterRecords));
          ColumnSortEvent.fire(grid, grid.getColumnSortList());
          restoreSelected();
       }

       /**
        * Adds rows to the grid's data provider. Only those rows that satisfy the supplied
        * regular expression are added, all the row columns are tested against the expression.
        *
        * @param   rows
        *          The rows to add.
        * @param   filterExp
        *          Regular expression.
        */
       public void addRows(TRowObject[] rows, RegExp filterExp)
       {
          addRows(Arrays.asList(rows), filterExp);
       }

       /**
        * Clears the grid and adds rows to the grid's data provider. This method keeps the current
        * grid selection.
        *
        * @param   rows
        *          The rows to set.
        */
       public void setRows(TRowObject[] rows)
       {
          clearGrid(true);
          addRows(rows);
          dataProvider.refresh();
       }

       /**
        * Clears the grid and adds rows to the grid's data provider. Only those rows that satisfy
        * the supplied regular expression are added, all the row columns are tested against
        * the expression.
        *
        * @param   rows
        *          The rows to set.
        * @param   filterExp
        *          Regular expression.
        */
       public void setRows(TRowObject[] rows, RegExp filterExp)
       {
          clearGrid(true);
          addRows(rows, filterExp);
          dataProvider.refresh();
          restoreSelected();
       }

       /**
        * Stores the currently selected rows.
        */
       private void storeSelected()
       {
          selected = new HashSet<>(selectionModel.getSelectedSet());
       }

       /**
        * Selects the rows stored by {@link #storeSelected()}.
        */
       private void restoreSelected()
       {
          if (selected != null)
          {
             List<TRowObject> list = dataProvider.getList();
             if (list != null)
             {
                for (TRowObject rec : selected)
                {
                   selectionModel.setSelected(rec, false);

                   int i = list.indexOf(rec);
                   if (i >= 0)
                   {
                      selectionModel.setSelected(list.get(i), true);
                   }
                }
             }
          }
       }
    }