LegacyCollection.java

/*
** Module   : LegacyCollection.java
** Abstract : Implementation of the builtin class.
**
** Copyright (c) 2019-2023, Golden Code Development Corporation.
**
** -#- -I- --Date-- --------------------------------------Description---------------------------------------
** 001 ME  20200519 First version, stubs taken by converting the skeleton using FWD.
** 002 ME  20210128 Implement this using a Java collection, simply override all from AbstratTTCollection.
** 003 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
**     ME  20210325 Decrement object reference when removed from collection.
**     CA  20210609 Updated INPUT/INPUT-OUTPUT parameters to the new approach, where they are explicitly 
**                  initialized at the method's execution, and not at the caller's arguments.
**     CA  20220120 Do not used TypeFactory.object when the OO reference must not be tracked or registered.
**                  Do not use TypeFactory.object for internal usages, use ObjectVar if the reference must 
**                  be tracked.
**                  All TypeFactory.object variable definitions must be done outside of the top-level block.
**     GES 20210501 Upgraded table-handle parameter processing to match API changes.
** 004 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
**                  dropped if is a no-op.
*/

/*
** 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.oo.core.collections;

import com.goldencode.p2j.util.*;
import com.goldencode.p2j.util.BlockManager.Action;
import com.goldencode.p2j.util.BlockManager.Condition;

import com.goldencode.p2j.oo.core.Assert;
import com.goldencode.p2j.oo.core.collections.AbstractTtcollection;
import com.goldencode.p2j.oo.lang._BaseObject_;
import com.goldencode.p2j.persist.TemporaryBuffer;

import static com.goldencode.p2j.report.ReportConstants.*;
import static com.goldencode.p2j.util.BlockManager.*;
import static com.goldencode.p2j.util.InternalEntry.Type;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Business logic (converted to Java from the 4GL source code
 * in OpenEdge/Core/Collections/Collection.cls).
 */
@LegacyResource(resource = "OpenEdge.Core.Collections.Collection")
@LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
public class LegacyCollection
extends AbstractTtcollection
{
   private List<object<? extends _BaseObject_>> objects;
   
   @LegacySignature(type = Type.EXECUTE)
   public void __core_collections_LegacyCollection_execute__()
   {
      onBlockLevel(Condition.ERROR, Action.THROW);
   }

   @LegacySignature(type = Type.CONSTRUCTOR)
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __core_collections_LegacyCollection_constructor__()
   {
      internalProcedure(LegacyCollection.class, this, "__core_collections_LegacyCollection_constructor__", new Block((Body) () -> 
      {
         __core_collections_AbstractTtcollection_constructor__();
         objects = new ArrayList<object<? extends _BaseObject_>>();
      }));
   }

   @LegacySignature(type = Type.CONSTRUCTOR, parameters = 
   {
      @LegacyParameter(name = "c", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT")
   })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __core_collections_LegacyCollection_constructor__(final object<? extends Icollection> _c)
   {
      object<? extends Icollection> c = TypeFactory.initInput(_c);
      
      internalProcedure(LegacyCollection.class, this, "__core_collections_LegacyCollection_constructor__", new Block((Body) () -> 
      {
         __core_collections_LegacyCollection_constructor__();
         addAll(c);
      }));
   }

   @LegacySignature(returns = "INTEGER", type = Type.GETTER, name = "Size")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public integer getSize()
   {
      return function(this, "Size", integer.class, new Block((Body) () -> {
         returnNormal(objects.size());
      }));
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Add", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical add(final object<? extends _BaseObject_> _p1)
   {
      object<? extends _BaseObject_> p1 = TypeFactory.initInput(_p1);

      return function(this, "Add", logical.class, new Block((Body) () -> {
         returnNormal(add_(p1));
      }));
   }
   
   private boolean add_(final object<? extends _BaseObject_> p1) {
      if (p1._isValid()) {
         ObjectOps.increment(p1.ref());
         return objects.add(p1);
      }
      
      return false;
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "AddArray", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", extent = -1, qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical addArray(final object<? extends _BaseObject_>[] _p1)
   {
      object<? extends _BaseObject_> p1[] = TypeFactory.initInput(_p1);

      return function(this, "AddArray", logical.class, new Block((Body) () -> {
         for (object<? extends _BaseObject_> obj : p1)
         {
            add_(obj);
         }

         returnNormal(true);
      }));
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "AddAll", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical addAll(final object<? extends Icollection> _p1)
   {
      object<? extends Icollection> p1 = TypeFactory.initInput(_p1);

      return function(this, "AddAll", logical.class, new Block((Body) () -> {
         if (ObjectOps.typeOf(p1, LegacyCollection.class).booleanValue())
         {
            for (object<? extends _BaseObject_> obj : ObjectOps.cast(p1, LegacyCollection.class).ref().objects)
            {
               add_(obj);
            }
            returnNormal(true);
         }
         else
         {
            returnNormal(super.addAll(p1));
         }
      }));
   }
   
   @LegacySignature(type = Type.METHOD, name = "Clear")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public void clear_()
   {
      internalProcedure(this, "Clear", new Block((Body) () ->
      {
         objects.clear();
      }));
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Contains", parameters = 
   {
      @LegacyParameter(name = "checkObject", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
   })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical contains(final object<? extends _BaseObject_> _checkObject)
   {
      object<? extends _BaseObject_> checkObject = TypeFactory.initInput(_checkObject);
      
      return function(LegacyCollection.class, this, "Contains", logical.class, new Block((Body) () ->
      {
         returnNormal(_find(checkObject).isValid());
      }));
   }
   
   protected object<? extends _BaseObject_> _find(
            final object<? extends _BaseObject_> checkObject)
   {
      if (checkObject._isValid())
      {
         List<object<? extends _BaseObject_>> items = objects.stream()
                  .filter(o -> o.equals(checkObject)).collect(Collectors.toList());

         // if more objects found (duplicate) 4GL sees it as ambiguous
         if (items.size() == 1)
         {
            return items.get(0);
         }

         // in 4GL objects are also matched using equals (LegacyEquals) 
         Optional<object<? extends _BaseObject_>> found = objects.stream()
                  .filter(o -> checkObject.ref().legacyEquals(o).booleanValue()).findFirst();

         if (found.isPresent())
         {
            return found.get();
         }
      }

      return new object(_BaseObject_.class);
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "ContainsAll", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical containsAll(final object<? extends Icollection> _p1)
   {
      object<? extends Icollection> p1 = TypeFactory.initInput(_p1);

      return function(this, "ContainsAll", logical.class, new Block((Body) () -> {

         Assert.notNull(p1, new character("Collection to check"));

         if (ObjectOps.typeOf(p1, LegacyCollection.class).booleanValue())
         {
            LegacyCollection other = ObjectOps.cast(p1, LegacyCollection.class).ref();

            if (other.objects.isEmpty())
               returnNormal(true);

            // this is handled like a set not collection 
            if (other.objects.size() > objects.size())
               returnNormal(false);

            returnNormal(!other.objects.stream().filter(o -> !_find(o)._isValid()).findFirst().isPresent());
         }
         else
         {
            returnNormal(super.containsAll(p1));
         }

      }));
   }
   
   @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Iterator", qualified = "openedge.core.collections.iiterator")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public object<? extends com.goldencode.p2j.oo.core.collections.Iiterator> iterator()
   {
      return function(this, "Iterator", object.class, new Block((Body) () -> {
         returnNormal(ObjectOps.newInstance(LegacyIterator.class, "III", new object(this),
                  new handle(new TransparentWrapper(objects)), ""));
      }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "IsEmpty")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical isEmpty()
   {
      return function(this, "IsEmpty", logical.class, new Block((Body) () -> {
         returnNormal(objects.isEmpty());
      }));
   }
   
   @LegacySignature(type = Type.METHOD, name = "ToTable", parameters = {
            @LegacyParameter(name = "p1", type = "HANDLE", mode = "OUTPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_STUB)
   @Override
   public void toTable(final OutputTableHandle _p1)
   {
      handle p1 = new handle();

      internalProcedure(AbstractTtcollection.class, this, "ToTable", new Block((Body) () ->
      {
         // TODO: create table from collection
         TemporaryBuffer.createDynamicTable(_p1, p1);
      }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Remove", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical remove(final object<? extends _BaseObject_> _p1)
   {
      object<? extends _BaseObject_> p1 = TypeFactory.initInput(_p1);

      return function(this, "Remove", logical.class, new Block((Body) () -> {
         object<? extends _BaseObject_> match = _find(p1);
         if (match._isValid())
         {
            ObjectOps.decrement(match.ref());
         }
         
         returnNormal(match._isValid() && objects.remove(match));
      }));
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "RemoveAll", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical removeAll(final object<? extends Icollection> _p1)
   {
      object<? extends Icollection> p1 = TypeFactory.initInput(_p1);

      return function(this, "RemoveAll", logical.class, new Block((Body) () -> {
         if (p1._isValid() && ObjectOps.typeOf(p1, LegacyCollection.class).booleanValue())
         {
            LegacyCollection other = ObjectOps.cast(p1, LegacyCollection.class).ref();
   
            List<object> matches = other.objects.stream().map(o -> _find(o)).filter(o -> o._isValid()).collect(Collectors.toList());
            
            matches.forEach(o -> {
               ObjectOps.decrement(o.ref());
            });
            
            returnNormal(objects.removeAll(matches));
         }
         else 
         {
            returnNormal(super.removeAll(p1));
         }
      }));
   }
   
   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "RetainAll", parameters = {
            @LegacyParameter(name = "p1", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical retainAll(final object<? extends Icollection> _p1)
   {
      object<? extends Icollection> p1 = TypeFactory.initInput(_p1);

      return function(this, "RetainAll", logical.class, new Block((Body) () -> {
         if (ObjectOps.typeOf(p1, LegacyCollection.class).booleanValue())
         {
            LegacyCollection other = ObjectOps.cast(p1, LegacyCollection.class).ref();
   
            List<?> matches = other.objects.stream().map(o -> _find(o)).filter(o -> o._isValid()).collect(Collectors.toList());
            
            returnNormal(objects.retainAll(matches));
         }
         else 
         {
            returnNormal(super.retainAll(p1));
         }
      }));
   }
   
   @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "ToArray", extent = -1, qualified = "progress.lang.object")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public object<? extends com.goldencode.p2j.oo.lang._BaseObject_>[] toArray()
   {
      return extentFunction(this, "ToArray", object.class, new Block((Body) () -> {
         returnExtentNormal(objects.toArray(new object[objects.size()]));
      }));
   }
   
   @LegacySignature(type = Type.METHOD, name = "Resize")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   protected void resize() {
      // NO-OP
   }
   
   @LegacySignature(type = Type.METHOD, name = "FindBufferUseObject", parameters = 
   {
      @LegacyParameter(name = "obj", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
   })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   protected void findBufferUseObject(final object<? extends _BaseObject_> _obj)
   {
   // no-op since this is using a java collection not 4gl temp-table
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Equals", parameters = 
   {
      @LegacyParameter(name = "o", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT")
   })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical legacyEquals(final object<? extends _BaseObject_> _o)
   {
      object<? extends _BaseObject_> o = TypeFactory.initInput(_o);
      
      return function(LegacyCollection.class, this, "Equals", logical.class, new Block((Body) () ->
      {
         
         if (super.legacyEquals(o).booleanValue())
            returnNormal(true);
         
         if (ObjectOps.typeOf(o, Icollection.class).booleanValue()) {
            object<? extends Icollection> other = ObjectOps.cast(o, Icollection.class);
            
            returnNormal(objects.size() == other.ref().getSize().intValue() &&
                     containsAll(other).booleanValue());
         }
         
         returnNormal(false);
      }));
   }
   
   protected Collection<object<? extends _BaseObject_>> getObjects()
   {
      return objects;
   }
}