/*
 * 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.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.base.CaseFormat;
import com.google.common.base.Converter;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;

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;


/**
 * Can be one of the given values.
 */
public class WithinSet implements 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"));


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

    return new WithinSet(subType, values);
  };

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

  public static final Joiner JOINER = Joiner.on(", ");

  /**
   * Convenience function that builds a WithinSet type of text members from an enum, making sure to convert
   * java-style upper case enum members to riskscape-style lower-underscore names, suitable for use in things
   * like options arrays, e.g. options: {style: ['low', 'down', 'dirty']}.
   *
   * It's assumed that binding code that goes the other way will be case insensitive (See EnumBinder)
   */
  public static WithinSet fromEnum(Class<?> enumClass) {

    if (!enumClass.isEnum()) {
      throw new IllegalArgumentException("Class is not an enum:" + enumClass);
    }
    @SuppressWarnings("unchecked") // see explicit check above
    Class<Enum<?>> castClass = (Class<Enum<?>>) enumClass;

    Converter<String, String> enumConverter = CaseFormat.UPPER_UNDERSCORE.converterTo(CaseFormat.LOWER_UNDERSCORE);

    List<String> labels = Arrays.stream(castClass.getEnumConstants())
        .map(e -> enumConverter.convert(e.name()))
        .collect(Collectors.toList());

    return new WithinSet(Types.TEXT, labels);
  }

  @Getter
  private final Set<?> allowed;

  @Getter
  private final Type underlyingType;

  public WithinSet(Type underlyingType, Object...objects) {
    this(underlyingType, Arrays.asList(objects));
  }

  public WithinSet(Type underlyingType, Collection<?> objects) {
    if (objects.isEmpty()) {
      throw new IllegalArgumentException("member set can not be empty");
    }

    this.underlyingType = underlyingType;
    try {
      this.allowed = ImmutableSet.copyOf(objects.stream().
          map(m -> underlyingType.coerce(m)).collect(Collectors.toSet()));
    } catch (CoercionException ex) {
      throw new IllegalArgumentException("member set must conform to underlying type", ex);
    }
  }


  @Override
  public Object coerce(Object value) {
    Object coerced = this.underlyingType.coerce(value);

    if (!allowed.contains(coerced)) {
      throw new CoercionException(value, this, "'%s' does not belong to set [%s]", value, allowedString());
    }

    return coerced;
  }

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

  public String allowedString() {
    return JOINER.join(allowed);
  }

  @Override
  public String toString() {
    return String.format("WithinSet(type=%s, allowed=[%s])", underlyingType, allowedString());
  }

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

  @Override
  public int hashCode() {
    return Objects.hashCode(this.underlyingType, this.allowed);
  }

 }
