# ListImages.java

    /*
    ** Module   : ListImages.java
    ** Abstract : an implementation of IImages COM interface
    **
    ** Copyright (c) 2019-2021, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description----------------------------------
    ** 001 MAG 20191106 Created initial version.
    ** 002 SBI 20200529 Implemented all required methods and changed newInstance to return handle
    ** 003 VVT 20210601 Missing @Override annotaion(s) added.
    */

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

    import java.util.*;
    import java.util.Map.*;

    import com.goldencode.p2j.comauto.*;
    import com.goldencode.p2j.ui.*;
    import com.goldencode.p2j.util.*;

    import static com.goldencode.p2j.ui.ocx.CollectionsErrorReasons.*;

    /**
     * A server side implementation of IImages COM interface
     *
     * @author mag
     *
     */
    @SuppressWarnings("rawtypes")
    public class ListImages
    extends ComInterface
    implements IImages
    {
       /** Maps keys to target images */
       private Map<String, comhandle> keysToImages = new LinkedHashMap<>();

       /** Lists all images */
       private List<comhandle> images = new LinkedList<>();

       /**
        * Constructor.
        *
        * @param   parent
        *          Parent widget.
        */
       private ListImages(GenericWidget parent)
       {
          super(IImages.class.getName(), parent);
       }

       /**
        * Factory method.
        *
        * @param    parent
        *           The image list parent widget.
        *
        * @return   The new instance wrapped by comhandle.
        */
       public static handle newInstance(GenericWidget parent)
       {
          return new handle(new ListImages(parent));
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComMethod(name = "ADD")
       public comhandle add(integer index, character key, comhandle picture)
       {
          if (key == null || key.isUnknown())
          {
             return new comhandle();
          }

          if (keysToImages.containsKey(key.getValue()))
          {
             ErrorManager.throwErrorWhileProcessingComponentProperty("ADD", KEY_NOT_UNIQUE.getReason());

             return new comhandle();
          }

          comhandle imageObj = ListImage.newInstance(parent, picture);

          images.add(imageObj);

          keysToImages.put(key.getValue(), imageObj);

          if (picture != null && picture.getResource() instanceof PictureObject)
          {
             PictureObject pictureObject = (PictureObject) picture.getResource();

             ((ImageListWidget) parent).addImage(new character(pictureObject.getImagePath()));
          }

          return imageObj;
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComMethod(name = "ADD")
       public comhandle add(ComParameter index, ComParameter key, ComParameter picture)
       {
          return add((integer) index.getValue(), (character) key.getValue(), (comhandle) picture.getValue());
       }

       /**
        * Returns a specific member of a Collection either by position.
        *
        * @param    index
        *           Collection position
        *
        * @return   The image handle at requested position or unknown if not found.
        */
       @Override
       @ComProperty(name = "ITEM")
       public comhandle getItem(NumberType index)
       {
          if (index == null || index.isUnknown())
          {
             return new comhandle();
          }

          return item(index.intValue());
       }

       /**
        * Returns the image comhandle reference by the given 1-based index.
        *
        * @param    index
        *           The given 1-based index
        *
        * @return   The image comhandle reference
        */
       private comhandle item(int index)
       {
          if (index <= 0 && index > images.size())
          {
             return new comhandle();
          }

          return images.get(index - 1);
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComProperty(name = "ITEM")
       public comhandle getItem(character key)
       {
          if (key == null || key.isUnknown())
          {
             return new comhandle();
          }

          return item(key.getValue());
       }

       /**
        * Returns the image comhandle reference by the given image key.
        *
        * @param    key
        *           The given image key
        *
        * @return   The image comhandle reference
        */
       private comhandle item(String key)
       {
          if (key == null)
          {
             return new comhandle();
          }

          return keysToImages.get(key);
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComMethod(name = "CLEAR")
       public void clear()
       {
          keysToImages.clear();

          while(!images.isEmpty())
          {
             comhandle imageReference = images.remove(0);

             ComObject unwrappedImage = imageReference.getResource();

             if (unwrappedImage != null)
             {
                unwrappedImage.deref();
             }
          }
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComProperty(name = "COUNT")
       public integer getCount()
       {
          return new integer(images.size());
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComProperty(name = "COUNT")
       public void setCount(integer count)
       {
          // Not used at runtime
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComMethod(name = "REMOVE")
       public void remove(NumberType index)
       {
          if (index == null || index.isUnknown())
          {
             ErrorManager.throwErrorWhileProcessingComponentProperty("REMOVE", INDEX_OUT_OF_BOUNDS.getReason());
          }

          remove(index.intValue());
       }

       /**
        * Remove a specific member of a collection.
        *
        * @param   index
        *          position inside collection, 1-based index.
        */
       public void remove(int index)
       {
          if (index <= 0 || index > images.size())
          {
             ErrorManager.throwErrorWhileProcessingComponentProperty("REMOVE", INDEX_OUT_OF_BOUNDS.getReason());
          }

          comhandle imageReference = images.remove(index - 1);

          String key = findKey(imageReference);

          keysToImages.remove(key);

          ComObject unwrappedImage = imageReference.getResource();

          if (unwrappedImage != null)
          {
             unwrappedImage.deref();
          }
       }

       /**
        * {@inheritDoc}
        */
       @Override
       @ComMethod(name = "REMOVE")
       public void remove(character key)
       {
          if (key == null || key.isUnknown())
          {
             ErrorManager.throwErrorWhileProcessingComponentProperty("REMOVE", INVALID_KEY.getReason());
          }

          remove(key.getValue());
       }

       /**
        * Remove a specific member of a collection.
        *
        * @param    key
        *           The image key
        */
       public void remove(String key)
       {
          comhandle imageReference = keysToImages.remove(key);

          if (imageReference != null)
          {
             images.remove(imageReference);

             ComObject unwrappedImage = imageReference.getResource();

             if (unwrappedImage != null)
             {
                unwrappedImage.deref();
             }
          }
          else
          {
             ErrorManager.throwErrorWhileProcessingComponentProperty("REMOVE", ELEMENT_NOT_FOUND.getReason());
          }
       }

       /**
        * Finds an image key.
        *
        * @param    imageReference
        *           The target image reference
        *
        * @return   The image key
        */
       String findKey(comhandle imageReference)
       {
          Entry<String, comhandle> found = findKeyValueEntry(imageReference);

          if (found != null)
          {
             return found.getKey();
          }

          return null;
       }

       /**
        * Finds an image position within this images list.
        *
        * @param    imageReference
        *           The target image reference
        *
        * @return   The image 0-based position within this images list
        */
       int findIndex(comhandle imageReference)
       {
          return images.indexOf(imageReference);
       }

       /**
        * Finds an image key and reference pair.
        *
        * @param    imageReference
        *           The target image reference
        *
        * @return   The image key and reference pair
        */
       private Entry<String, comhandle> findKeyValueEntry(comhandle imageReference)
       {
          Optional<Entry<String, comhandle>> found = keysToImages.entrySet().stream().filter(
                   entry -> entry.getValue() == imageReference).findFirst();

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

          return null;
       }
    }