# ProcessesView.java

    /*
    ** Module   : ProcessesView.java
    ** Abstract : ProcessesView is a view to manage process accounts.
    **
    ** Copyright (c) 2017, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description----------------------
    ** 001 SBI 20170601 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.processes;

    import java.util.EnumMap;
    import java.util.List;
    import java.util.Set;

    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.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.SelectionChangeEvent;
    import com.google.inject.Inject;

    /**
     * ProcessesView is a view to manage process accounts.
     */
    public class ProcessesView
    extends BaseViewWithUiHandlers<ProcessesUIHandlers>
    implements ProcessesPresenter.MyView
    {
       /** GWT UI Creator */
       interface Binder
       extends UiBinder<Widget, ProcessesView>
       {}

       /** The process accounts table view */
       @UiField(provided = true)
       DataGrid<TaggedName> processesGrid = GridHelper.<TaggedName>create();

       /** The peer certificates table view */
       @UiField(provided = true)
       DataGrid<TaggedName> certsGrid = GridHelper.<TaggedName>create();

       /** The Refresh Process Accounts button */
       @UiField
       Button refreshProcesses;

       /** The Add Process Account button */
       @UiField
       Button addProcess;

       /** The Delete Process Accounts button */
       @UiField
       Button deleteProcessAccounts;

       /** The Clone Process Account button */
       @UiField
       Button cloneProcess;

       /** The Edit Process Account button */
       @UiField
       Button editProcess;

       /** The Disable Process Account button */
       @UiField
       Button disableProcess;

       /** The Refresh Peer Certificates button */
       @UiField
       Button refreshCerts;

       /** The Assign Peer Certificate button */
       @UiField
       Button assignCert;

       /** The Switch to Certificates button */
       @UiField
       Button switchToCerts;

       /** modal container */
       @UiField
       Widget modalFragment;

       /** The Switch to ACLs button */
       @UiField
       Button switchToACLs;

       /** The parent container for the Add/Edit Process Account Definition view */
       @UiField
       FlowPanel procDefModal;

       /** The process accounts grid handle */
       private final GridHandle<TaggedName> psGridHandle;

       /** The peer certificates grid handle */
       private final GridHandle<TaggedName> certsGridHandle;

       /** The Clone Process View */
       private final CloneProcessView cloneProcessView;

       /**
        * Constructs this view, used by MPV gwtplatform of ArcBees Inc.
        *
        * @param    binder
        *           UI creator
        * @param    cloneProcessView
        *           Clone process account child view
        */
       @Inject
       public ProcessesView(Binder binder,
                            CloneProcessView cloneProcessView)
       {
          initWidget(binder.createAndBindUi(this));
          this.psGridHandle = GridHelper.<TaggedName>initListGrid(
                   processesGrid,
                   true,
                   new GridHelper.ColumnInfo<TaggedName>(
                            "Process Account",
                            (tn) -> tn.getName(),
                            null),
                   new GridHelper.ColumnInfo<TaggedName>(
                            "Description",
                            (tn) -> tn.getTag(),
                            null));

          this.certsGridHandle = GridHelper.<TaggedName>initListGrid(
                   certsGrid,
                   false,
                   new GridHelper.ColumnInfo<TaggedName>(
                            "Alias",
                            (tn) -> tn.getName(),
                            null),
                   new GridHelper.ColumnInfo<TaggedName>(
                            "Description",
                            (tn) -> tn.getTag(),
                            null));
          this.cloneProcessView = cloneProcessView;

          /* setup modal content slot and add child dialogs */
          setupModalSlot(ProcessesPresenter.MODAL_CONTENT, modalFragment);
          addDialog(cloneProcessView);

          psGridHandle.getSelectionModel().addSelectionChangeHandler(new SelectionChangeEvent.Handler()
          {
             @Override
             public void onSelectionChange(SelectionChangeEvent event)
             {
                Set<TaggedName> selected = psGridHandle.getSelected();
                getUiHandlers().onProcessSelectionChanged(selected);
             }
          });

          this.certsGridHandle.getSelectionModel().addSelectionChangeHandler(new SelectionChangeEvent.Handler()
          {
             @Override
             public void onSelectionChange(SelectionChangeEvent event)
             {
                TaggedName selectedCert = certsGridHandle.getSelectedSingle();
                getUiHandlers().onCertificateSelectionChanged(selectedCert);
             }
          });
       }

       /**
        * 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[]
                   {
                      refreshProcesses,
                      addProcess,
                      deleteProcessAccounts,
                      cloneProcess,
                      editProcess,
                      disableProcess,
                      switchToACLs,
                      refreshCerts,
                      assignCert,
                      switchToCerts
                   };
       }

       /**
        * Sets the all process accounts table model.
        *
        * @param    processes
        *           The array of process accounts given by tagged names
        */
       @Override
       public void setProcesses(TaggedName[] processes)
       {
          this.psGridHandle.clearGrid();
          if (processes != null)
          {
             this.psGridHandle.addRows(processes);
             this.psGridHandle.getDataProvider().flush();
          }
       }

       /**
        * Sets the peer certificates table model.
        *
        * @param    certs
        *           The array of peer certificates given by tagged names
        */
       @Override
       public void setCerts(TaggedName[] certs)
       {
          this.certsGridHandle.clearGrid();
          if (certs != null)
          {
             this.certsGridHandle.addRows(certs);
             this.certsGridHandle.getDataProvider().flush();
          }
       }

       /**
        * The Refresh Processes button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("refreshProcesses")
       void onRefreshProcesses(ClickEvent event)
       {
          getUiHandlers().onRefreshProcesses();
       }

       /**
        * The Refresh Certificates button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("refreshCerts")
       void onRefreshCerts(ClickEvent event)
       {
          getUiHandlers().onRefreshCerts();
       }

       /**
        * The Add Process button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("addProcess")
       void onAddProcess(ClickEvent event)
       {
          getUiHandlers().showAddProcessAccountDialog();
       }

       /**
        * The Edit process account button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("editProcess")
       void onEditProcess(ClickEvent event)
       {
          TaggedName selected = psGridHandle.getSelected().toArray(new TaggedName[1])[0];
          getUiHandlers().showEditProcessAccountDialog(selected);
       }

       /**
        * The Clone process account button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("cloneProcess")
       void onCloneProcess(ClickEvent event)
       {
          TaggedName selected = psGridHandle.getSelected().toArray(new TaggedName[1])[0];
          getUiHandlers().setupCloneProcessAccountDialog(selected);
       }

       /**
        * The Disable process account button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("disableProcess")
       public void onDisableProcess(ClickEvent event)
       {
          TaggedName ps = psGridHandle.getSelected().toArray(new TaggedName[0])[0];
          getUiHandlers().disableProcessAccount(ps);
       }

       /**
        * The Delete selected process accounts button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("deleteProcessAccounts")
       public void onDeleteProcessAccounts(ClickEvent event)
       {
          Set<TaggedName> accounts = psGridHandle.getSelected();
          getUiHandlers().deleteProcessAccounts(accounts);
       }

       /**
        * The Switch To ACLs button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("switchToACLs")
       public void onSwitchToACLs(ClickEvent event)
       {
          TaggedName selected = psGridHandle.getSelected().toArray(new TaggedName[1])[0];
          getUiHandlers().switchToACLs(selected);
       }

       /**
        * The Switch To Certificates button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("switchToCerts")
       public void onSwitchToCerts(ClickEvent event)
       {
          TaggedName selected = certsGridHandle.getSelected().toArray(new TaggedName[1])[0];
          certsGridHandle.select(selected);
          getUiHandlers().switchToCertificates(selected);
       }

       /**
        * Gets a reference to the Clone Process Account View.
        *
        * @return   The Clone Group View
        */
       @Override
       public CloneProcessView getCloneProcessView()
       {
          return cloneProcessView;
       }

       /**
        * Tests if the given process account is selected now.
        *
        * @param    account
        *           The given process account
        *
        * @return   True iff this process account is selected now
        */
       @Override
       public boolean isProcessAccountSelected(TaggedName account)
       {
          Set<TaggedName> selected = psGridHandle.getSelected();
          return selected.contains(account) && selected.size() == 1;
       }

       /**
        * Tests if the given set of process accounts is selected now.
        *
        * @param    accounts
        *           The given set of process accounts
        *
        * @return   True iff this given set of process accounts is selected now
        */
       @Override
       public boolean isProcessAccountsSelected(Set<TaggedName> accounts)
       {
          return psGridHandle.getSelected().containsAll(accounts);
       }

       /**
        * Tests if the given peer certificate is selected.
        *
        * @param    cert
        *           The given peer certificate
        *
        * @return   True iff the given peer certificate is selected, otherwise false.
        */
       @Override
       public boolean isCertificateSelected(TaggedName cert)
       {
          Set<TaggedName> selected = certsGridHandle.getSelected();
          // has single selection model
          return selected.contains(cert);
       }

       /**
        * Toggles the label of the Disable/Enable process account button.
        *
        * @param    selectedAccount
        *           The selected process account
        * @param    enabled
        *           The enabled flag which true value indicates that the target buttons label
        *           becomes "Disable Process", otherwise this label becomes "Enable Process".
        */
       @Override
       public void toggleDisableProcessButton(TaggedName selectedAccount, boolean enabled)
       {
          if (isProcessAccountSelected(selectedAccount))
          {
             if (enabled)
             {
                this.disableProcess.setText("Disable Process");
             }
             else
             {
                this.disableProcess.setText("Enable Process");
             }
          }
       }

       /**
        * Assigns the given peer certificate to the selected process account.
        *
        * @param    selectedAccount
        *           The selected process account
        * @param    alias
        *           The peer certificate alias name
        */
       @Override
       public void setAssignedCert(TaggedName selectedAccount, String alias)
       {
          if (isProcessAccountSelected(selectedAccount))
          {
             List<TaggedName> certsList = this.certsGridHandle.getDataProvider().getList();
             certsList.forEach(cert ->
             {
                if (cert.getName().equals(alias))
                {
                   Scheduler.get().scheduleDeferred(new ScheduledCommand()
                   {
                      @Override
                      public void execute()
                      {
                         certsGridHandle.getSelectionModel().setSelected(cert, true);
                      }
                   });
                }
             });
          }
       }

       /**
        * Selects the target process account by its tagged name.
        *
        * @param    account
        *           The tagged name
        */
       @Override
       public void selectProcessAccount(TaggedName account)
       {
          Scheduler.get().scheduleDeferred(new ScheduledCommand()
          {
             @Override
             public void execute()
             {
                psGridHandle.getSelectionModel().setSelected(account, true);
             }
          });
       }

       /**
        * Selects the target process account by its account name.
        *
        * @param    name
        *           The account name
        */
       @Override
       public void selectProcessAccountByName(String name)
       {
          psGridHandle.clearSelection();
          psGridHandle.getDataProvider().getList().forEach(psAccount -> {
             if (psAccount.getName().equals(name))
             {
                Scheduler.get().scheduleDeferred(new ScheduledCommand()
                {
                   @Override
                   public void execute()
                   {
                      psGridHandle.getSelectionModel().setSelected(psAccount, true);
                   }
                });
             }
          });
       }

       /**
        * Returns the parent container where the Add/Edit Process Account Definition View will be
        * revealed in.
        *
        * @return   The parent container for the Add/Edit Process Account Definition View.
        */
       @Override
       public HasWidgets getProcDefModalParent()
       {
          return procDefModal;
       }

       /**
        * The Assign Certificate button click handler.
        *
        * @param    event
        *           Click event
        */
       @UiHandler("assignCert")
       void onAssignCert(ClickEvent event)
       {
          Set<TaggedName> selectedProcesses = psGridHandle.getSelected();
          TaggedName selectedProcess = selectedProcesses.toArray(new TaggedName[1])[0];
          Set<TaggedName> selectedCerts = certsGridHandle.getSelected();
          TaggedName selectedCert = selectedCerts.toArray(new TaggedName[1])[0];
          getUiHandlers().assignCertificateToProcess(selectedCert, selectedProcess);
       }

       /**
        * 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, Object>(
                   ReportParameters.class);
          parameters.put(ReportParameters.SELECTION, psGridHandle.getSelected().toArray(
                   new TaggedName[psGridHandle.getSelected().size()]));
          parameters.put(ReportParameters.TITLE, "Processes");
          parameters.put(ReportParameters.REPORT_ID, Reports.PROCESSES);
          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 psGridHandle.getSelected().size();
          }

          return psGridHandle.getDataProvider().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 = psGridHandle.getSelected().size();
          int allRecordsNumber = psGridHandle.getDataProvider().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 + " process accounts being printed. Continue?</h4>";
                   }
                   else if (allRecordsNumber == 1)
                   {
                      hlpText = "<h4>1 process account being printed. Continue?</h4>";
                   }
                   else
                   {
                      hlpText = "<h4>There are no process accounts to print. Continue?</h4>";
                   }
                }

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

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

                break;
          }

          return null;
       }

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