# LazyUndoable.java

    /*
    ** Module   : Undoable.java
    ** Abstract : defines 'lazy' undoable support for BDT and other runtime resources.
    **
    ** Copyright (c) 2016-2020, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --------------------------------------Description---------------------------------------
    ** 001 CA  20160627 Created initial version; provides a 'lazy' way for resoures to register
    **                  themselves for undoable support; when the resource is first changed, it will
    **                  look up the stack and register itself with all blocks until the block which
    **                  declared it was found or until the first block which already saved it is
    **                  reached.
    ** 002 GES 20200807 Removed context-local lookups in checkUndoable().
    ** 003 SP  20240422 Modified checkUndoable() to use processUndoables(false),
    **                  to check only if a transaction is active
    */

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

    import java.util.function.*;

    import com.goldencode.p2j.util.TransactionManager.UndoableHelper;

    /**
     * Defines behaviour for objects which can be rolled back at runtime.
     */
    public abstract class LazyUndoable
    implements Undoable
    {
       /** Flag indicating if this instance is undoable. */
       private transient boolean undoable = false;

       /** Flag indicating if this instance was changed. */
       private transient boolean changed = false;

       /** Flag indicating if this instance is currently rolling back. */
       private transient boolean rollingBack = false;

       /** Flag indicating if this resource was defined as a NEW GLOBAL SHARED. */
       private transient boolean global = false;

       /**
        * This is the transaction nesting level, where the undoable was last changed.  When exiting a
        * tx block, this value gets decremented - this number will reflect the last block (inclusive)
        * where the object was registered.  When registering, it goes up the stack and registers only
        * with tx blocks with a tx level greater than this value.
        */
       private transient int transLevel = -1;

       /** Helper object to access context-local data in the {@link TransactionManager}. */
       private transient UndoableHelper undoableHelper = null;

       /**
        * Set this undoable as defined via a NEW GLOBAL SHARED statement.
        *
        * @param    global
        *           <code>true</code> to indicate a global resource.
        */
       protected final void setGlobal(boolean global)
       {
          this.global = global;
       }

       /**
        * Get this undoable's global state.
        *
        * @return   the {@link #global} flag.
        */
       protected final boolean isGlobal()
       {
          return global;
       }

       /**
        * Notification that a transaction block was finished.
        */
       protected final void popBlock()
       {
          transLevel = transLevel - 1;
       }

       /**
        * Check if this variable has changed.  This check resets the {@link #changed} flag.
        *
        * @return   The state of the {@link #changed} flag.
        */
       protected final boolean changed()
       {
          try
          {
             return changed;
          }
          finally
          {
             changed = false;
          }
       }

       /**
        * Rollback this instance to the state in the given copy.
        *
        * @param    copy
        *           The state to which the instance is rolledback.
        */
       protected final void rollback(Undoable copy)
       {
          if (!changed)
          {
             return;
          }

          changed = false;

          try
          {
             rollingBack = true;

             assign(copy);
          }
          finally
          {
             rollingBack = false;
          }
       }

       /**
        * Check if this instance is undoable.
        *
        * @return   The {@link #undoable} flag state.
        */
       protected boolean isUndoable()
       {
          return undoable;
       }

       /**
        * Mark this instance as undoable and save the transaction level where it was created.
        *
        * @param    transLevel
        *           The transaction nesting level where this instance was created.
        */
       protected final void markUndoable(int transLevel)
       {
          this.undoable = true;
          this.transLevel = transLevel;
       }

       /**
        * Check if this undoable has changed; if so, and we are in a transaction block (and not
        * {@link #rollingBack rolling back}), then register this instance with all blocks up the stack,
        * which were started after the object's {@link #transLevel last save transaction level}.
        *
        * @param    changed
        *           Flag indicating if this undoable has changed or not.
        */
       protected void checkUndoable(boolean changed)
       {
          if (!isUndoable() || rollingBack)
          {
             return;
          }

          checkUndoable(null, null, changed);
       }

       /**
        * Check if this undoable has changed; if so, and we are in a transaction block (and not
        * {@link #rollingBack rolling back}), then register this instance with all blocks up the stack,
        * which were started after the object's {@link #transLevel last save transaction level}.
        *
        * @param    newValue
        *           To value to compare against, when deciding if this undoable is changed.
        */
       protected void checkUndoable(Undoable newValue)
       {
          if (!isUndoable() || rollingBack)
          {
             return;
          }

          checkUndoable(newValue, null, false);
       }

       /**
        * Check if this undoable has changed; if so, and we are in a transaction block (and not
        * {@link #rollingBack rolling back}), then register this instance with all blocks up the stack,
        * which were started after the object's {@link #transLevel last save transaction level}.
        *
        * @param    newValue
        *           To value to compare against, when deciding if this undoable is changed.
        */
       protected void checkUndoable(Supplier<Undoable> newValue)
       {
          if (!isUndoable() || rollingBack)
          {
             return;
          }

          checkUndoable(null, newValue, false);
       }

       /**
        * Get the transaction level at which this instance was last registered.
        *
        * @return    The {@link #transLevel}.
        */
       int getTransLevel()
       {
          return transLevel;
       }

       /**
        * Check if this undoable has changed; if so, and we are in a transaction block (and not
        * {@link #rollingBack rolling back}), then register this instance with all blocks up the stack,
        * which were started after the object's {@link #transLevel last save transaction level}.
        * <p>
        * If the {@code force} argument is {@code true}, then the {@code nv1} and
        * {@code nv2} arguments are ignored; otherwise, if {@code nv2} is not-null, then
        * this will be used to compare against, while {@code nv1} is used in the last case.
        *
        * @param    nv1
        *           To value to compare against, when deciding if this undoable is changed.
        * @param    nv2
        *           To value to compare against, when deciding if this undoable is changed, wrapped
        *           in a supplier, to avoid instantiating a new object.
        * @param    force
        *           When {@code true}, ignore the previous two arguments and force the undoable
        *           registration.
        */
       private void checkUndoable(Undoable nv1, Supplier<Undoable> nv2, boolean force)
       {
          if (undoableHelper == null)
          {
             undoableHelper = TransactionManager.getUndoableHelper();
          }

          if (!undoableHelper.processUndoables(false))
          {
             return;
          }

          // TODO: check if is not faster to mark as 'changed' any assignment, no matter if the right-side
          // is the same state as the left-side or not (it matters if there was an assignment)
          if (!force)
          {
             ErrorManager.ErrorHelper errHlp = undoableHelper.getErrorHelper();

             // if the changed flag is on, then bypass this
             boolean pendingError = false;

             try
             {
                if (nv2 != null && errHlp.isPending())
                {
                   pendingError = true;

                   errHlp.setPending(false);
                }

                Undoable newValue = (nv1 == null ? nv2.get() : nv1);

                if (this.equals(newValue))
                {
                   return;
                }
             }
             finally
             {
                if (pendingError)
                {
                   errHlp.setPending(true);
                }
             }
          }

          // this will walk the entire TM$WorkArea.blocks stack and will post a pair of (this, snapshot)
          // to all the blocks with a tx level greater than this value (were started AFTER the last
          // change in this undoable)
          this.transLevel = undoableHelper.registerUndoable(this);

          // mark this var as changed
          this.changed = true;
       }
    }