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

import static hdf.hdf5lib.H5.*;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import hdf.hdf5lib.H5;
import lombok.EqualsAndHashCode;
import lombok.Getter;

import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.hdf5.H5Object;

/**
 * Represents an H5 data type, with some conveniences for mapping these to Riskscape types.  Each type should produce
 * native java objects that can be coerced easily by the riskscape type it maps to
 */
@EqualsAndHashCode(callSuper = false)
public abstract class H5Type extends H5Object {
  public static H5Type build(long id) {
    int classId = H5Tget_class(id);
    String superClassName = H5Tget_class_name(classId);

    if (superClassName.equals("H5T_COMPOUND")) {
      return new H5CompoundType(id);
    } else if (superClassName.equals("H5T_ARRAY")) {
      return new H5ArrayType(id);
    }
    if (superClassName.equals("H5T_INTEGER")) {
      return new H5IntegerType(id);
    }
    if (superClassName.equals("H5T_FLOAT")) {
      return new H5FloatType(id);
    }
    if (superClassName.equals("H5T_ENUM")) {
      return new H5EnumType(id);
    }
    if (superClassName.equals("H5T_STRING")) {
      return new H5StringType(id);
    }
    if (superClassName.equals("H5T_VLEN")) {
      return new H5VlenType(id);
    }

    throw new RuntimeException("unknown type " + superClassName);
  }

  /**
   * The size in bytes of any element of this type.
   */
  @Getter
  private final long dataSize;

  protected H5Type(long ptr) {
    super(ptr);
    dataSize = H5Tget_size(ptr);
  }
  /**
   * @return a Riskscape type that mirrors the HD5 data type
   */
  public abstract Type toType();

  /**
   * @return a java object that represents the data that was stored in the outBuf if it was of this data type.
   * This java object should be coercable in to the type returned from {@link #toType()}
   */
  public abstract Object read(ByteBuffer outBuf, int offset);

  /**
   * @return the H5 library's name for this type
   */
  public String getClassName() {
    return H5.H5Tget_class_name(H5.H5Tget_class(ptr));
  }

  @Override
  public abstract String toString();

  /**
   * @return true if this type is, or contains something, of variable length.  As yet, this H5 support
   * in this plugin can not read datasets of variable length type
   */
  public abstract boolean isVariableLength();

  /**
   * Special case read method for reading variable length data from the result of a call to H5.h5d_readVL.  Note that
   * the type that should be doing the reading is the member type, not the vlen type itself.
   * @param rawBytes the result of reading a vlen type from a dataset by {@link
   * nz.org.riskscape.hdf5.H5Dataset#readVlenElements(H5DataSpace, H5DataSpace, int)} via {@link
   * H5#H5DreadVL(long, long, long, long, long, Object[])}. These bytes are the raw data representation
   * of each selected element that was read.
   *
   * @return a variable length number of elements of this type
   */
  public Object[] readVlen(byte[] rawBytes) {
    // raw bytes holds all the data for a variable-length array (or 'ragged' array) of a given type.
    // Wrap it in a ByteBuffer so we can use it with H5Type#read
    ByteBuffer byteBuffer = ByteBuffer.wrap(rawBytes);
    byteBuffer.order(ByteOrder.nativeOrder());

    // work out the variable-length size of the array we need to read
    final int memberSize = (int) this.getDataSize();
    int numVLenElements = rawBytes.length / memberSize;
    Object[] elements = new Object[numVLenElements];

    // read each element's raw data based on its underlying H5Type
    for (int i = 0, offset = 0; i < numVLenElements; i++, offset += memberSize) {
      elements[i] = this.read(byteBuffer, offset);
    }

    return elements;
  }

  @Override
  public void close() {
    H5.H5Tclose(ptr);
  }
}
