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

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.model.ModelParameter;
import nz.org.riskscape.problem.Problem;

/**
 * Contains the aspects of a parameter that the user can customize themselves. In general,
 * these aspects relate to how the parameter is presented to other users, especially via a UI.
 * A ParameterTemplate can be associated with one or more {@link ModelParameter}s.
 */
@RequiredArgsConstructor
@Data
public class ParameterTemplate {

  public static final ParameterTemplate EMPTY = new ParameterTemplate(
      Optional.empty(),
      Optional.empty(),
      Collections.emptySet(),
      Collections.emptyList(),
      Optional.empty());

  /**
   * A parameter can have a set of pre-defined choices, i.e. an options list. Each
   * choice can also have an optional user-friendly label. In UI terms, these
   * options can be used in a drop-down select, or a multiselect.
   */
  @Data
  @RequiredArgsConstructor
  public static class Choice {
    private final Object value;
    private final Optional<String> label;
  }

  private final Optional<String> label;

  private final Optional<String> description;

  private final Set<ParameterProperty> properties;

  private final List<Choice> choices;

  private final Optional<String> defaultValue;

  public ParameterTemplate(Optional<String> label, Optional<String> description, Set<ParameterProperty> properties,
                           List<Choice> choices) {
    this(label, description, properties, choices, Optional.empty());
  }

  public boolean hasProperty(ParameterProperty property) {
    return getProperty(property).isPresent();
  }

  /**
   * Returns the specified property, if present in the template. This is mainly useful for
   * {@link KeyValueProperty}, where the actual ParameterProperty instance has more info associated with it.
   */
  @SuppressWarnings("unchecked")
  public <T extends ParameterProperty> Optional<T> getProperty(T property) {
    return properties.stream()
        .filter(p -> p.equals(property))
        .map(p -> (T) p)
        .findFirst();
  }

  public ParameterTemplate withLabel(String newLabel) {
    return new ParameterTemplate(Optional.of(newLabel), description, properties, choices, defaultValue);
  }

  /**
   * @return a cloned copy of this template with the newProperties specified
   */
  public ParameterTemplate withProperties(Set<ParameterProperty> newProperties) {
    return new ParameterTemplate(label, description, newProperties, choices, defaultValue);
  }

  public ParameterTemplate withDefaultValue(String newDefault) {
    return new ParameterTemplate(label, description, properties, choices, Optional.of(newDefault));
  }

  public List<Problem> validate(BindingContext context, Object bound) {
    List<Problem> problems = new ArrayList<>();
    for (ParameterProperty property : getProperties()) {
      problems.addAll(property.validate(context, bound));
    }
    return problems;
  }

  /**
   * Returns all properties for the parameter. These properties may be explicitly
   * set by the user, implied (e.g. MIN_VALUE implies NUMERIC), or inferred (e.g.
   * if no properties are explicitly set, then we can tell from the default value
   * `[1,2,3]` that the parameter is both NUMERIC and a LIST).
   */
  public Set<ParameterProperty> getProperties() {
    Set<ParameterProperty> allProperties = new LinkedHashSet<>();
    for (ParameterProperty property : properties) {
      allProperties.add(property);
      // for consistency, also include any properties that are implied
      allProperties.addAll(property.getImplied());
    }
    return allProperties;
  }
}
