# ProcessAccountDefinition.java

    /*
    ** Module   : ProcessAccountDefinition.java
    ** Abstract : ProcessAccountDefinition is a view and controller delegate to add and to edit
    **            process accounts.
    **
    ** Copyright (c) 2017, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ----------------Description----------------------
    ** 001 HC 20170521 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 com.goldencode.p2j.admin.*;
    import com.goldencode.p2j.admin.client.*;
    import com.goldencode.p2j.admin.client.application.*;
    import com.goldencode.p2j.admin.client.widget.dialog.*;
    import com.goldencode.p2j.admin.client.widget.dialog.InputDialog.*;
    import com.google.gwt.user.client.ui.*;
    import com.google.inject.*;
    import org.gwtbootstrap3.extras.select.client.ui.*;

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

    /**
     * Implements the add and edit process accounts use cases.
     */
    public class ProcessAccountDefinition
    extends Composite
    {
       /**
        * Process Account model
        */
       public static class ProcessData
       {
          /**
           * Creates the process account model.
           *
           * @param    processDef
           *           The process account definition
           * @param    extDef
           *           The account extension data
           */
          public ProcessData(ProcessDef processDef, Serializable extDef)
          {
             this.processDef = processDef;
             this.extDef = extDef;
          }

          /** The process account definition */
          public ProcessDef processDef;

          /** The account extension data */
          public Serializable extDef;
       }

       /** The account extension */
       @Inject(optional = true)
       AccountExtension acctExtension;

       /** The common input dialogs provider */
       private final Provider<InputDialog> inputDialogProvider;

       /** The administration server interface */
       private final com.goldencode.p2j.admin.shared.AdminServiceAsync adminService;

       /** The server alarm manager */
       private final Alarm alarm;

       /** The edit boolean flag which true value indicates the edit use case.*/
       private boolean edit;

       /** The common input dialog */
       private InputDialog inputDialog;

       /** The account name field */
       private Field acctName;

       /** The account disabled field */
       private Field acctDisabled;

       /** The account description field */
       private Field description;

       /** The peer certificates field */
       private Field certificates;

       /** The server mode field */
       private Field server;

       /** The master mode field */
       private Field master;

       /**
        * Creates the Process Account Definition delegate.
        *
        * @param    inputDialogProvider
        *           The injected common input dialogs provider
        * @param    adminService
        *           The injected administration server interface
        * @param    alarm
        *           The injected server alarm manager
        */
       @Inject
       public ProcessAccountDefinition(Provider<InputDialog> inputDialogProvider,
                                       com.goldencode.p2j.admin.shared.AdminServiceAsync adminService,
                                       Alarm alarm)
       {
          this.inputDialogProvider = inputDialogProvider;
          this.adminService = adminService;
          this.alarm = alarm;
       }

       /**
        * Builds the dialog's fields of the Process Account Definition View.
        *
        * @param    pDef
        *           The given process account definition
        * @param    doneHandler
        *           The completion consumer
        */
       public void build(ProcessDef pDef, Consumer<Boolean> doneHandler)
       {
          edit = pDef != null;
          inputDialog = inputDialogProvider.get();
          buildStandardFields(pDef, items ->
          {
             if (items != null)
             {
                inputDialog.setLabelSize(3);
                Item[] itemsArray = items.toArray(new Item[0]);
                if (acctExtension != null)
                {
                   Map<AccountExtension.StandardFields, Field> standardFields;
                   standardFields = new HashMap<>();
                   standardFields.put(AccountExtension.StandardFields.ACCT_NAME, acctName);
                   acctExtension.createFields(edit,
                                              inputDialog,
                                              standardFields,
                                              itemsArray,
                                              allItems ->
                   {
                      buildStep2(pDef, allItems.toArray(new Item[0]), doneHandler);
                   });
                }
                else
                {
                   buildStep2(pDef, itemsArray, doneHandler);
                }
             }
             else
             {
                doneHandler.accept(false);
             }
          });
       }

       /**
        * Shows the Process Definition View dialog.
        *
        * @param    parent
        *           The parent container for the Process Definition View dialog
        * @param    pDef
        *           The process account definition
        * @param    doneHandler
        *           The consumer of the process account model
        */
       public void show(HasWidgets parent, ProcessDef pDef, Consumer<ProcessData> doneHandler)
       {
          inputDialog.show(parent, false, values ->
          {
             if (values == null)
             {
                inputDialog.dismiss();
                doneHandler.accept(null);
                return;
             }

             saveUIData(pDef, values);
             Serializable extData = null;
             if (acctExtension != null)
             {
                extData = acctExtension.getExtData();
             }
             inputDialog.dismiss();
             doneHandler.accept(new ProcessData(pDef, extData));
          });
       }

       /**
        * Builds the extended process account fields.
        *
        * @param    pDef
        *           The given process account definition
        * @param    items
        *           The standard process account fields
        * @param    doneHandler
        *           The completion consumer
        */
       private void buildStep2(ProcessDef pDef, Item[] items, Consumer<Boolean> doneHandler)
       {
          inputDialog.build("Process Account Definition", items);

          HasEnabled nameW = (HasEnabled) inputDialog.getWidget(acctName);
          nameW.setEnabled(!edit);

          if (acctExtension != null)
          {
             acctExtension.onDialogBuilt(inputDialog, doneHandler);
          }
          else
          {
             doneHandler.accept(true);
          }
       }

       /**
        * Builds the standard dialog's fields for the given process account definition.
        *
        * @param    pDef
        *           The given process account definition
        * @param    doneHandler
        *           The consumer of the dialog's fields
        */
       private void buildStandardFields(ProcessDef pDef, Consumer<ArrayList<Item>> doneHandler)
       {
          ArrayList<Item> res = new ArrayList<>(20);
          loadUIData(data ->
          {
             acctName = new Field("Account Name", pDef == null ? "" : pDef.subjectId);
             res.add(acctName);

             acctDisabled = new Field("Account is Disabled", pDef == null ? false : !pDef.enabled);
             res.add(acctDisabled);

             description = new Field("Description",
                                     pDef == null || pDef.description == null ? "" :
                                                                                pDef.description,
                                     true);
             res.add(description);

             certificates = new SelectField("Certificates", data.certificates,
                                            pDef == null || pDef.alias == null ? "" : pDef.alias,
                                            null, true);
             res.add(certificates);

             server = new Field("Server", pDef == null ? false : pDef.server);
             res.add(server);

             master = new Field("Master", pDef == null ? false : pDef.master);
             res.add(master);

             doneHandler.accept(res);
          });
       }

       /**
        * Loads UIData asynchronously and invokes the given result's consumer if this action is
        * completed successfully.
        *
        * @param    doneHandler
        *           The given result's consumer
        */
       private void loadUIData(Consumer<UIData> doneHandler)
       {
          MultiCallback mc = new MultiCallback(adminService, alarm);
          AdminCallback<TaggedName[]> certsCb = mc.newCallback();

          mc.onDone(() ->
          {
             if (mc.isSuccess())
             {
                TaggedName[] certstn = certsCb.getResult();

                List<Option> certs = new ArrayList<>();
                Option empty = new Option();
                certs.add(empty);
                for (TaggedName certtn : certstn)
                {
                   Option opt = new Option();
                   opt.setValue(certtn.getName());
                   opt.setText(certtn.getName());
                   opt.setSubtext(certtn.getTag());
                   certs.add(opt);
                }

                doneHandler.accept(new UIData(certs));
             }
          });

          adminService.listPeerCerts(false, certsCb);
       }

       /**
        * Saves the user's input data into the target process account definition.
        *
        * @param    target
        *           The target process account definition
        * @param    values
        *           The map of the dialog's fields to their values
        */
       private void saveUIData(ProcessDef target, Map<Field, Object> values)
       {
          target.subjectId = (String) values.get(acctName);
          String cert = (String) values.getOrDefault(certificates, null);
          target.alias = cert.isEmpty() ? null : cert;
          target.enabled = !(boolean) values.get(acctDisabled);
          target.description = (String) values.get(description);
          target.server = (boolean) values.get(server);
          target.master = (boolean) values.get(master);
       }

       /**
        * Holds the peer certificates.
        */
       private static class UIData
       {
          /** The list of option elements filled with certificates tagged names */
          List<Option> certificates;

          /**
           * Creates this UI data container
           *
           * @param    certificates
           *           The list of option elements filled with certificates tagged names
           */
          public UIData(List<Option> certificates)
          {
             this.certificates = certificates;
          }
       }
    }