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

import java.util.List;
import java.util.Objects;

import lombok.Getter;
import nz.org.riskscape.engine.typexp.AST;
import nz.org.riskscape.engine.typexp.AST.ComplexType;
import nz.org.riskscape.engine.typexp.ComplexTypeConstructor;
import nz.org.riskscape.engine.typexp.TypeArgumentException;
import nz.org.riskscape.engine.typexp.TypeBuilder;

/**
 * Type that limits value to be within a specified range.
 */
public class WithinRange implements Type, WrappingType {

  public static final ComplexTypeConstructor TYPE_CONSTRUCTOR = (TypeBuilder typeBuilder, ComplexType type) -> {
    List<AST> args = type.args();

    Type subType = typeBuilder.expectType(args.remove(0), ast
        -> new TypeArgumentException(type, "First argument must be a type"));

    if (!(subType instanceof Rangeable)) {
      throw new TypeArgumentException(type, "First argument must be a rangeable type, such as a number");
    }

    if (args.size() != 2) {
      throw new TypeArgumentException(type, String.format(
          "Exactly 2 trailing arguments are required, but %d given",
          args.size()));
    }

    List<Object> coerced = typeBuilder.expectConstantsOfType(type, subType, args, 1);

    return new WithinRange((Rangeable) subType, coerced.remove(0), coerced.remove(0));
  };

  public static final TypeInformation TYPE_INFORMATION = new TypeInformation(
      "range",
      WithinRange.class,
      Object.class,
      TYPE_CONSTRUCTOR
  );

  @Getter
  private Rangeable underlyingType;

  @Getter
  private Comparable<Object> max;
  @Getter
  private Comparable<Object> min;

  @SuppressWarnings("unchecked")
  public WithinRange(Rangeable type, Object min, Object max) {
    this.underlyingType = type;

    if (!Comparable.class.isAssignableFrom(internalType())) {
      throw new IllegalArgumentException("the internal type of %s does not implement comparable, this is probably a "
          + "programming error");
    }

    this.min = (Comparable<Object>) type.coerce(min);
    this.max = (Comparable<Object>) type.coerce(max);
  }

  @Override
  public Object coerce(Object value) {
    checkForNull(value);

    @SuppressWarnings("unchecked")
    Comparable<Object> coerced = (Comparable<Object>) this.underlyingType.coerce(value);

    if (coerced.compareTo(min) < 0) {
      throw new CoercionException(value, this, "'%s' is less than minimum of %s", value, min);
    } else if (max.compareTo(coerced) < 0) {
      throw new CoercionException(value, this, "'%s' exceeds maximum of %s", value, max);
    }

    return coerced;
  }

  @Override
  public Class<?> internalType() {
    return underlyingType.internalType();
  }

  @Override
  public String toString() {
    return String.format("WithinRange(type=%s, min=%s, max=%s)", underlyingType, min, max);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof WithinRange) {
       WithinRange rhs = (WithinRange) obj;
       return rhs.underlyingType.equals(this.underlyingType) && rhs.max.equals(this.max) && rhs.min.equals(this.min);
    } else {
      return false;
    }
  }

  @Override
  public int hashCode() {
    return Objects.hash(underlyingType, min, max);
  }

}
