/*
 * This file is part of the Meeds project (https://meeds.io/).
 * Copyright (C) 2020 Meeds Association
 * contact@meeds.io
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.exoplatform.services.rest.util;

import org.exoplatform.services.rest.ExtMultivaluedMap;
import org.exoplatform.services.rest.uri.UriPattern;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @param <V> {@link org.exoplatform.services.rest.RequestFilter} or
 *          {@link org.exoplatform.services.rest.ResponseFilter}
 */
public class UriPatternMap<V> extends HashMap<UriPattern, List<V>> implements ExtMultivaluedMap<UriPattern, V>
{

   /**
    * Generated by Eclipse.
    */
   private static final long serialVersionUID = 8248982446381545144L;

   /**
    * @param uriPattern the key
    * @return List of Object mapped to specified <code>uriPattern</code>. Method
    *         never return null, empty List instead.
    */
   public List<V> getList(UriPattern uriPattern)
   {
      List<V> l = get(uriPattern);
      if (l == null)
      {
         l = new ArrayList<V>();
         put(uriPattern, l);
      }
      return l;
   }

   /**
    * {@inheritDoc}
    */
   public void add(UriPattern uriPattern, V value)
   {
      if (value == null)
         return;
      List<V> list = getList(uriPattern);
      list.add(value);
   }

   /**
    * {@inheritDoc}
    */
   public V getFirst(UriPattern uriPattern)
   {
      List<V> list = getList(uriPattern);
      return list != null && list.size() > 0 ? list.get(0) : null;
   }

   /**
    * {@inheritDoc}
    */
   public void putSingle(UriPattern uriPattern, V value)
   {
      if (value == null)
         return;
      List<V> list = getList(uriPattern);
      list.clear();
      list.add(value);
   }

}
