/*
 * 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 nz.org.riskscape.engine.data;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.Identified;
import nz.org.riskscape.util.ListUtils;

/**
 * Bookmarks point to some resource to be used for risk modeling.
 */
@RequiredArgsConstructor
@Builder
@EqualsAndHashCode
public class Bookmark implements Identified {

  /**
   * Construct an anonymous bookmark from a URI.  Useful for tests :)
   */
  public static Bookmark fromURI(URI uri) {
    return Bookmark.fromURI(uri, uri.toString());
  }

  public static Bookmark fromURI(URI uri, String id) {
    return new Bookmark(id, uri.toString(), null, uri, true)
        .addUnparsed(parseQueryString(uri.getQuery()));
  }

  // static scoped for testing
  static Map<String, List<?>> parseQueryString(String query) {
    if (Strings.isNullOrEmpty(query)) {
      return ImmutableMap.of();
    }

    return Arrays.asList(query.split("&"))
      .stream()
      .map(kv -> kv.split("=", 2))
      .filter(kv -> kv.length == 2)
      .collect(Collectors.toMap(
          kv -> kv[0],
          kv -> Arrays.asList(decode(kv[1])),
          ListUtils::concat
      ));
  }

  private static String decode(String string) {
    try {
      return URLDecoder.decode(string, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("Utf-8 is missing, wah", e);
    }
  }

  @Getter
  private final String id;
  @Getter
  private final String description;
  @Getter
  private final String format;

  /**
   * Contains a potentially modified location, set to be absolute based on the location of the bookmark itself.  For
   * a bookmark from a file, it will be relative to the directory the bookmark was in.
   */
  @Getter
  private final URI location;

  /**
   * Contains extra, unparsed, keys and values from the bookmark definition that a particular resolver can make use of
   */
  @Getter
  private final Map<String, List<?>> unparsed = Maps.newHashMap();

  /**
   * If true, this Bookmark has not been fetched from an identified collection, but instead constructed, probably from
   * a URI.  The id is probably the text the user supplied and the URI is going to be something that was set or
   * synthezised on the user's behalf
   */
  @Getter
  private final boolean fromURI;

  public Bookmark(String id, String description, String format, URI location, Map
  <String, List<String>> unparsed) {
    this(id, description, format, location, false);
    this.unparsed.putAll(unparsed);
  }

  public Bookmark addUnparsed(Map<String, List<?>> toAdd) {
    unparsed.putAll(toAdd);
    return this;
  }

  /**
   * @return a copy of the parameter map in this bookmark.
   */
  public Map<String, List<?>> getParamMap() {
    Map<String, List<?>> map = new HashMap<>();
    map.putAll(unparsed);
    map.put("location", Arrays.asList(location));

    if (!Strings.isNullOrEmpty(format)) {
      map.put("format", Arrays.asList(format));
    }
    if (!Strings.isNullOrEmpty(description)) {
      map.put("description", Arrays.asList(description));
    }

    // wrap it in an immutable map - this should catch the case where we try to mutate the map thinking it'll
    // update the bookmark
    return Map.copyOf(map);
  }

  @Override
  public String toString() {
    return String.format("Bookmark[id: %s, location: %s]", id, location);
  }

  @Override
  public Bookmark clone() {
    return new Bookmark(id, description, format, location, fromURI).addUnparsed(unparsed);
  }

  public Bookmark withFormat(String newFormat) {
    return new Bookmark(id, description, newFormat, location, fromURI).addUnparsed(unparsed);
  }

  public Bookmark withLocation(URI newLocation) {
    return new Bookmark(id, description, format, newLocation, fromURI).addUnparsed(unparsed);
  }
}
