/*
 * 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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import com.google.common.collect.Lists;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Chars;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;

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;

/**
 * Basic list type that can convert various arrays and list types to the required type
 */
public class RSList implements Type, ContainingType {

  private static final List<RSList> INSTANCES = Arrays.asList(
      new RSList(Types.ANYTHING, false),
      new RSList(Nullable.ANYTHING, false),
      new RSList(Types.INTEGER, false),
      new RSList(Types.FLOATING, false),
      new RSList(Types.TEXT, false),
      new RSList(Types.GEOMETRY, false)
  );

  public static RSList create(Type memberType) {
    for (RSList rsList : INSTANCES) {
      if (rsList.getMemberType().equals(memberType)) {
        return rsList;
      }
    }
    return new RSList(memberType, true);
  }

  public static final RSList LIST_ANYTHING = create(Nullable.ANYTHING);

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

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

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

    return RSList.create(subType);
  };

  public static final TypeInformation TYPE_INFORMATION = new TypeInformation(
     "list",
     RSList.class,
     List.class,
     TYPE_CONSTRUCTOR
  );

  /**
   * @deprecated use {@link #create(Type)} instead - reduces the amount of identical types being allocated
   * All Riskscape code has been ported to use create, but there may be functions etc out there that are using this old
   * constructor.  We might want to log a stack trace when this is used if it becomes functionally important that the
   * new static constructor be used.
   */
  @Deprecated
  public RSList(Type memberType) {
    this.memberType = memberType;
  }

  /**
   * Internal, non-deprecated constructor - ignored flag is here just to provide a non-deprecated alternative
   */
  protected RSList(Type memberType, boolean ignored) {
    this.memberType = memberType;
  }

  private final Type memberType;

  @SuppressWarnings("unchecked")
  @Override
  public Object coerce(Object value) throws CoercionException {
    if (value.getClass().isArray()) {

      @SuppressWarnings("rawtypes")
      java.util.List coerced;
      if (value.getClass() == float[].class) {
        coerced = Floats.asList((float[]) value);
      } else if (value.getClass() == double[].class) {
        coerced = Doubles.asList((double[]) value);
      } else if (value.getClass() == byte[].class) {
        coerced = Bytes.asList((byte[]) value);
      } else if (value.getClass() == short[].class) {
        coerced = Shorts.asList((short[]) value);
      } else if (value.getClass() == char[].class) {
        coerced = Chars.asList((char[]) value);
      } else if (value.getClass() == int[].class) {
        coerced = Ints.asList((int[]) value);
      } else if (value.getClass() == long[].class) {
        coerced = Longs.asList((long[]) value);
      } else {
        coerced = Arrays.asList((Object[]) value);
      }


      // we need a copy before we start replacing things
      // XXX implement an optimistic version that checks before creating a new list?
      coerced = Lists.newArrayList(coerced);
      coerced.replaceAll((raw) -> memberType.coerce(raw));

      return coerced;
    }

    if (value instanceof java.util.List) {
      java.util.List<Object> asList = (java.util.List<Object>) value;
      ArrayList<Object> newList = new ArrayList<>(asList.size());

      for (Object object : asList) {
        newList.add(memberType.coerce(object));
      }

      return newList;
    }

    throw new CoercionException(value, this);
  }

  @Override
  public Class<?> internalType() {
    return java.util.List.class;
  }

  @Override
  public Struct asStruct() {
    return Struct.of("value", this);
  }

  public Type getMemberType() {
    return memberType;
  }

  @Override
  public int estimateSize(Object entry) {
    int total = 0;
    @SuppressWarnings("rawtypes")
    java.util.List asList = (java.util.List) entry;
    for (Object object : asList) {
      total += memberType.estimateSize(object);
    }
    return total;
  }

  @Override
  public void toBytes(DataOutputStream os, Object toWrite) throws IOException {
    java.util.List<?> listToWrite = (java.util.List<?>) toWrite;
    int members = listToWrite.size();
    os.writeInt(members);
    for (Object object : listToWrite) {
      this.memberType.toBytes(os, object);
    }
  }

  @Override
  public Object fromBytes(DataInputStream in) throws IOException {
    Object[] beingRead = new Object[in.readInt()];

    for (int i = 0; i < beingRead.length; i++) {
      beingRead[i] = this.memberType.fromBytes(in);
    }

    return Arrays.asList(beingRead);
  }

  @Override
  public String toString() {
    return String.format("List[%s]", memberType);
  }

  @Override
  public int hashCode() {
    int hash = 3;
    hash = 89 * hash + Objects.hashCode(this.memberType);
    return hash;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final RSList other = (RSList) obj;
    return Objects.equals(this.memberType, other.memberType);
  }

  @Override
  public Type getContainedType() {
    return memberType;
  }

}
