/*
 * 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.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

import lombok.Getter;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.typeset.IdentifiedType;
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;

/**
 * Wraps another type to allow values to be null.
 */
public class Nullable implements Type, ContainingType {

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

    if (args.size() != 1) {
      throw new TypeArgumentException(ct, "one argument expected");
    }

    Type subType = typeBuilder.expectType(args.get(0), ast
        -> new TypeArgumentException(ct, "nullable expects a type argument"));

    return Nullable.of(subType);
  };

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

  public static final Nullable TEXT = new Nullable(Types.TEXT);
  public static final Nullable BOOLEAN = new Nullable(Types.BOOLEAN);
  public static final Nullable INTEGER = new Nullable(Types.INTEGER);
  public static final Nullable FLOATING = new Nullable(Types.FLOATING);
  public static final Nullable DECIMAL = new Nullable(Types.DECIMAL);
  public static final Nullable ANYTHING = new Nullable(Types.ANYTHING);
  public static final Nullable DATE = new Nullable(Types.DATE);
  public static final Nullable GEOMETRY = new Nullable(Types.GEOMETRY);

  // TODO this whole method should become part of the type system's rules, not a static method on a built in type
  public static boolean is(Type toCheck) {
    if (toCheck instanceof IdentifiedType) {
      //LinkedType is a special wrapping type that we do want to access the underlying type
      //to do the nullable test on.
      return ((IdentifiedType)toCheck).getUnderlyingType() instanceof Nullable;
    }
    return toCheck instanceof Nullable;
  }

  public static Type ifTrue(boolean flag, Type wrapped) {
    if (flag) {
      return Nullable.of(wrapped);
    } else {
      return wrapped;
    }
  }

  public static Type of(Type wrapped) {
    if (wrapped.find(Nullable.class).isPresent()) {
      return wrapped;
    } else if (wrapped == Types.TEXT) {
      return TEXT;
    } else if (wrapped == Types.BOOLEAN) {
      return BOOLEAN;
    } else if (wrapped == Types.INTEGER) {
      return INTEGER;
    } else if (wrapped == Types.FLOATING) {
      return FLOATING;
    } else if (wrapped == Types.DECIMAL) {
      return DECIMAL;
    } else if (wrapped == Types.DATE) {
      return DATE;
    }
    return new Nullable(wrapped);
  }

  @Getter
  private final Type containedType;

  protected Nullable(Type wrapped) {
    this.containedType = wrapped;
  }

  @Override
  public Object coerce(Object value) throws CoercionException {
    if (value == null) {
      return null;
    } else if (value instanceof Optional) {
      Optional<?> opt = (Optional<?>) value;
      if (opt.isPresent()) {
        return containedType.coerce(opt.get());
      } else {
        return null;
      }
    } else {
      return containedType.coerce(value);
    }
  }

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

  @Override
  public Struct asStruct() {
    if (getContainedType() instanceof Struct) {
      Struct contained = (Struct) getContainedType();
      Struct mapped = Struct.of();
      for (StructMember member : contained.getMembers()) {
        mapped = mapped.add(member.getKey(), Nullable.of(member.getType()));
      }
      return mapped;
    } else {
      return Struct.of(SimpleType.DEFAULT_MEMBER_NAME, this);
    }
  }

  @Override
  public int hashCode() {
    return containedType.hashCode();
  }

  @Override
  public boolean equals(Object rhs) {
    if (rhs instanceof Nullable) {
      Nullable rhsNullable = (Nullable) rhs;
      return rhsNullable.containedType.equals(this.containedType);
    } else {
      return false;
    }
  }

  @Override
  public String toString() {
    return "Nullable[" + containedType.toString() + "]";
  }

  @Override
  public int estimateSize(Object entry) {
    return 1 + containedType.estimateSize(entry);
  }

  @Override
  public void toBytes(DataOutputStream os, Object toWrite) throws IOException {
    if (toWrite == null) {
      os.writeBoolean(false);
    } else {
      os.writeBoolean(true);
      containedType.toBytes(os, toWrite);
    }
  }

  @Override
  public Object fromBytes(DataInputStream in) throws IOException {
    boolean present = in.readBoolean();

    if (present) {
      return containedType.fromBytes(in);
    } else {
      return null;
    }
  }

  @Override
  public boolean isNullable() {
    return true;
  }

  /**
   * @return true if any of the given types are Nullable, e.g. `Type#find(Nullabe.class).isPresent()` is true
   */
  public static boolean any(Type... types) {
    return any(List.of(types));
  }

  /**
   * @return true if any of the given types are Nullable, e.g. `Type#find(Nullabe.class).isPresent()` is true
   */
  public static boolean any(List<Type> types) {
    for (Type type: types) {
      if(type.isNullable() || type.find(Nullable.class).isPresent()) {
        return true;
      }
    }
    return false;
  }

  public static Type strip(Type mightBeNullable) {
    return mightBeNullable.find(Nullable.class).map(n -> n.getContainedType()).orElse(mightBeNullable);
  }

  // Shortcut for Nullable.strip(type).getUnwrappedType()
  public static Type unwrap(Type mightBeNullable) {
    return mightBeNullable
        .find(Nullable.class).map(n -> n.getContainedType())
        .orElse(mightBeNullable)
        .getUnwrappedType();
  }

  /**
   * Apply a type-returning function to a type with null removed, applying nullable to the result if the given type was
   * nullable
   * @param mightBeNullable a type, possible nullable
   * @param wrappingFunction a function to apply to the non-nullable part of mightBeNullable
   * @return the result of the wrappingFunction, surrounded by a nullable type if mightBeNullable was nullable
   */
  public static Type rewrap(Type mightBeNullable, Function<Type, Type> wrappingFunction) {
    Type stripped = Nullable.strip(mightBeNullable);
    return ifTrue(stripped != mightBeNullable, wrappingFunction.apply(stripped));
  }

}
