/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * 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 for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed 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 should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package org.riskscape.cli;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Nullable;

import org.geotools.api.feature.simple.SimpleFeature;
import org.geotools.api.feature.type.AttributeDescriptor;

import com.google.common.base.Objects;

/**
 * A map interface to a {@link SimpleFeature} which
 */
public class FeatureBackedStructMap implements Map<String, Object> {

  private final SimpleFeature feature;
  private final Set<java.util.Map.Entry<String, Object>> entrySet;

  private class AttrEntry implements Map.Entry<String, Object> {

    private final AttributeDescriptor ad;

    AttrEntry(AttributeDescriptor ad) {
      this.ad = ad;
    }

    @Override
    public String getKey() {
      return ad.getLocalName();
    }

    @Override
    public Object getValue() {
      return feature.getAttribute(ad.getName());
    }

    @Override
    public Object setValue(Object value) {
      throw new UnsupportedOperationException();
    }

    @Override
    public boolean equals(@Nullable Object object) {
      if (object instanceof Entry) {
        Entry<?, ?> that = (Entry<?, ?>) object;
        return Objects.equal(this.getKey(), that.getKey())
            && Objects.equal(this.getValue(), that.getValue());
      }
      return false;
    }

    @Override
    public int hashCode() {
      String k = getKey();
      Object v = getValue();
      //CHECKSTYLE:OFF
      return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
      //CHECKSTYLE:ON
    }

    /**
     * Returns a string representation of the form {@code {key}={value}}.
     */
    @Override
    public String toString() {
      return getKey() + "=" + getValue();
    }

  }

  public FeatureBackedStructMap(SimpleFeature feature) {
    this(feature, null);
  }

  /**
   * Construct a FeatureBackedStructMap backed by the given feature, filtering to just those attributes named in
   * attributeNames
   * @param feature the feature to represent in a map
   * @param attributeNames the set of attributes to filter the attributes in feature by
   */
  public FeatureBackedStructMap(SimpleFeature feature, Set<String> attributeNames) {
    this.feature = feature;
    this.entrySet = feature.getFeatureType().getAttributeDescriptors().stream().
        filter(ad -> attributeNames == null || attributeNames.contains(ad.getLocalName())).
        map(ad -> new AttrEntry(ad)).collect(Collectors.toSet());
  }

  public SimpleFeature getFeature() {
    // leaky abstraction much?
    return feature;
  }

  @Override
  public Set<java.util.Map.Entry<String, Object>> entrySet() {
    return entrySet;
  }

  @Override
  public int size() {
    return this.entrySet.size();
  }

  @Override
  public boolean isEmpty() {
    return size() == 0;
  }

  @Override
  public boolean containsKey(Object key) {
    return this.entrySet.stream().filter(entry -> entry.getKey().equals(key)).findAny().isPresent();
  }

  @Override
  public boolean containsValue(Object value) {
    return values().contains(value);
  }

  @Override
  public Object get(Object key) {
    return this.entrySet.stream()
        .filter(entry -> entry.getKey().equals(key))
        .findFirst()
        .map(Entry::getValue).orElse(null);
  }

  @Override
  public Object put(String key, Object value) {
    throw new UnsupportedOperationException();
  }

  @Override
  public Object remove(Object key) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void putAll(Map<? extends String, ? extends Object> m) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void clear() {
    throw new UnsupportedOperationException();
  }

  @Override
  public Set<String> keySet() {
    return entrySet().stream().map(Entry::getKey).collect(Collectors.toSet());
  }

  @Override
  public Collection<Object> values() {
    return entrySet().stream().map(Entry::getValue).collect(Collectors.toList());
  }

  @Override
  public String toString() {
    return entrySet().stream().map(Entry::toString).collect(Collectors.joining(", ", "[", "]"));
  }

}
