# MultipartEntity.java

    /*
    ** Module   : MultipartEntity.java
    ** Abstract : Implementation of the builtin class.
    **
    ** Copyright (c) 2019-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
    ** 001 CA  20190526 First version, stubs taken by converting the skeleton using FWD.
    ** 002 IAS 20190527 Added multipart support.
    ** 003 CA  20191024 Added method support levels and updated the class support level.
    ** 004 ME  20200414 Complete implementation as per OE 11.7.4.
    **         20201123 Assert positive index on remove (OE 12.2).
    ** 005 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy signature.
    ** 006 ME  20210303 Increment/decrement object references for entity parts.
    **     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.
    **     ME  20210929 Fix return object on getPart.
    ** 007 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.net;

    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.*;
    import com.goldencode.p2j.oo.lang.*;

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

    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * Business logic (converted to Java from the 4GL source code
     * in OpenEdge/Net/MultipartEntity.cls).
     */
    @LegacyResource(resource = "OpenEdge.Net.MultipartEntity")
    @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
    public class MultipartEntity
    extends BaseObject
    implements ISupportMultipartEntity
    {
       // in OE is possible to add parts unordered and even have gaps between part numbers
       private class OrderedPart {
          int num;
          object<? extends MessagePart> entity;

          OrderedPart(int num, object<? extends MessagePart> entity) {
             this.num = num;
             this.entity = entity;
          }
       }

       /** Multipart boundary */
       private character boundary = TypeFactory.character();

       /** Epilogue */
       private character epilogue = TypeFactory.character();

       /** Prologue */
       private character prologue = TypeFactory.character();

       /** Parts */
       private List<OrderedPart> parts = new ArrayList<OrderedPart>();

       /**
        * Execute method.
        */
       @LegacySignature(type = Type.EXECUTE)
       public void __net_MultipartEntity_execute__()
       {
          onBlockLevel(Condition.ERROR, Action.THROW);
       }

       /**
        * Get multipart boundary.
        *
        * @return boundary.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Boundary")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       @Override
       public character getBoundary()
       {
          return function(this, "Boundary", character.class, new Block((Body) () ->
          {
             returnNormal(boundary);
          }));
       }

       /**
        * Set multipart boundary.
        *
        * @param _var multipart boundary.
        */
       @LegacySignature(type = Type.SETTER, name = "Boundary", parameters =
       {
          @LegacyParameter(name = "var", type = "CHARACTER", mode = "INPUT")
       })
       @Override
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void setBoundary(final character _var)
       {
          character var = TypeFactory.initInput(_var);

          internalProcedure(this, "Boundary", new Block((Body) () ->
          {
             Assert.notNullOrEmpty(var, new character("Multipart boundary"));

             boundary.assign(var);
          }));
       }

       /**
        * Get epilogue.
        *
        * @return epilogue.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Epilogue")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getEpilogue()
       {
          return function(this, "Epilogue", character.class, new Block((Body) () ->
          {
             returnNormal(epilogue);
          }));
       }

       /**
        * Set epilogue.
        *
        * @param _var epilogue.
        */
       @LegacySignature(type = Type.SETTER, name = "Epilogue", parameters =
       {
          @LegacyParameter(name = "var", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void setEpilogue(final character _var)
       {
          character var = TypeFactory.initInput(_var);

          internalProcedure(this, "Epilogue", new Block((Body) () ->
          {
             Assert.notNull(var, new character("Multipart epilogue"));
             epilogue.assign(var);
          }));
       }

       /**
        * Get prologue.
        *
        * @return prologue.
        */
       @LegacySignature(returns = "CHARACTER", type = Type.GETTER, name = "Prologue")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public character getPrologue()
       {
          return function(this, "Prologue", character.class, new Block((Body) () ->
          {
             returnNormal(prologue);
          }));
       }

       /**
        * Set prologue.
        *
        * @param _var prologue.
        */
       @LegacySignature(type = Type.SETTER, name = "Prologue", parameters =
       {
          @LegacyParameter(name = "var", type = "CHARACTER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void setPrologue(final character _var)
       {
          character var = TypeFactory.initInput(_var);

          internalProcedure(this, "Prologue", new Block((Body) () ->
          {
             Assert.notNull(var, new character("Multipart prologue"));
             prologue.assign(var);
          }));
       }

       /**
        * Get number of parts.
        *
        * @return number of parts.
        */
       @LegacySignature(returns = "INTEGER", type = Type.GETTER, name = "Size")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public integer getSize()
       {
          return function(this, "Size", integer.class, new Block((Body) () ->
          {
             returnNormal(new integer(parts.size()));
          }));
       }

       /**
        * Constructor.
        */
       @LegacySignature(type = Type.CONSTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_MultipartEntity_constructor__()
       {
          internalProcedure(this, "__net_MultipartEntity_constructor__", new Block((Body) () ->
          {
             __lang_BaseObject_constructor__();
             setBoundary(SecurityOps.convertUniversalUIDToGlobalUID());
          }));
       }

       /**
        * Destructor.
        */
       @LegacySignature(type = Type.DESTRUCTOR)
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void __net_MultipartEntity_destructor__()
       {
          internalProcedure(this, "__net_MultipartEntity_destructor__", new Block((Body) () ->
          {
             clearParts();;
          }));
       }

       /**
        * Add message part.
        *
        * @param _part message part.
        *
        * @return number of parts.
        */
       @LegacySignature(returns = "INTEGER", type = Type.METHOD, name = "AddPart", parameters =
       {
          @LegacyParameter(name = "part", type = "OBJECT", qualified = "openedge.net.messagepart", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public integer addPart(final object<? extends MessagePart> _part)
       {
          object<? extends MessagePart> part = TypeFactory.initInput(_part);

          return function(this, "AddPart", integer.class, new Block((Body) () ->
          {
             integer partNum = new integer(parts.size() + 1);

             setPart(partNum, part);

             returnNormal(partNum);
          }));
       }

       /**
        * Clear parts.
        */
       @LegacySignature(type = Type.METHOD, name = "ClearParts")
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public void clearParts()
       {
          internalProcedure(this, "ClearParts", new Block((Body) () -> {
             this.parts.forEach(p -> ObjectOps.decrement(p.entity));
             this.parts.clear();
          }));
       }

       /**
        * Get parts with given contentId
        *
        * @param _contentId contentId to be found
        *
        * @return parts with given contentId
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "GetPart", extent = -1, qualified = "openedg<e.net.messagepart", parameters = {
                @LegacyParameter(name = "contentId", type = "CHARACTER", mode = "INPUT") })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
       public object<? extends MessagePart>[] getPart(final character _contentId)
       {
          character contentId = TypeFactory.initInput(_contentId);

          return extentFunction(this, "GetPart", object.class, new Block((Body) () ->
          {
             Assert.notNull(contentId, new character("Content ID"));

             List<object<? extends MessagePart>> parts = this.parts.stream().filter(p -> CompareOps.equals(contentId, p.entity.ref().getContentId()))
                      .map(p -> p.entity).collect(Collectors.toList());

             if (parts.isEmpty())
                returnExtentNormal(TypeFactory.objectExtent(MessagePart.class, false));
             else
                returnExtentNormal(parts.toArray(new object[parts.size()]));
          }));
       }

       /**
        * Get part by number.
        *
        * @param _n part number.
        *
        * @return part no n.
        */
       @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "GetPart", extent = -1, qualified = "openedge.net.messagepart", parameters =
       {
          @LegacyParameter(name = "n", type = "INTEGER", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public object<? extends MessagePart> getPart(final integer _n)
       {
          integer n = TypeFactory.initInput(_n);
          object<? extends MessagePart> part = TypeFactory.object(MessagePart.class);

          return function(this, "GetPart", object.class, new Block((Body) () -> {
             Assert.isPositive(n, new character("Part num"));

             Optional<OrderedPart> opt = parts.stream().filter(p -> p.num == n.intValue()).findFirst();

             if (opt.isPresent())
                part.assign(opt.get().entity);

             returnNormal(part);
          }));
       }

       /**
        * Remove part by number.
        *
        * @param _n part number.
        *
        * @return <code>true</code> if removed.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "RemovePart", parameters = {
                @LegacyParameter(name = "n", type = "INTEGER", mode = "INPUT") })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
       public logical removePart(final integer _n)
       {
          integer n = TypeFactory.initInput(_n);

          return function(this, "RemovePart", logical.class, new Block((Body) () ->
          {
             Assert.isPositive(n, new character("Part num"));

             Optional<OrderedPart> found = this.parts.stream().filter(p -> p.num == n.intValue()).findFirst();

             if (found.isPresent())
             {
                OrderedPart part = found.get();

                this.parts.remove(part);
                ObjectOps.decrement(part.entity);

                // if removed reorder all parts that comes after (the OE way)
                List<OrderedPart> past = this.parts.stream().filter(p -> p.num > n.intValue())
                         .sorted((p1, p2) -> p1.num - p2.num).collect(Collectors.toList());
                int partNum = n.intValue();

                for (OrderedPart p : past)
                {
                   p.num = partNum++;
                }
             }

             returnNormal(new logical(found.isPresent()));
          }));
       }

       /**
        * Add a part
        *
        * @param _p1 The part number being added.
        * @param _p2 The part being added.
        *
        * @return <code>true</code> if part was replaced.
        */
       @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "SetPart", parameters =
       {
          @LegacyParameter(name = "p1", type = "INTEGER", mode = "INPUT"),
          @LegacyParameter(name = "p2", type = "OBJECT", qualified = "openedge.net.messagepart", mode = "INPUT")
       })
       @LegacyResourceSupport(supportLvl = CVT_LVL_FULL|RT_LVL_FULL)
       public logical setPart(final integer _p1, final object<? extends MessagePart> _p2)
       {
          integer partNum = TypeFactory.initInput(_p1);
          object<? extends com.goldencode.p2j.oo.net.MessagePart> entity = TypeFactory.initInput(_p2);

          return function(this, "SetPart", logical.class, new Block((Body) () -> {
             Assert.isPositive(partNum, new character("Part num"));
             Assert.notNull(entity, new character("Entity"));

             ObjectOps.increment(entity);

             Optional<OrderedPart> part = parts.stream().filter(p -> p.num == partNum.intValue()).findFirst();

             if(part.isPresent()) {
                ObjectOps.decrement(part.get().entity);

                part.get().entity = entity;
             } else {
                parts.add(new OrderedPart(partNum.intValue(), entity));
             }

             returnNormal(new logical(part.isPresent()));
          }));
       }
    }