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

import static hdf.hdf5lib.H5.*;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

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

/**
 * A dataspace is a handle used to either read *from* or *to* a dataset. In the 'read from' case,
 * the dataspace is a read-view into a {@link H5Dataset}. The same H5Dataset can support multiple
 * dataspaces reading from it at once. Because the H5Dataspace selects specific elements from the
 * dataset to read, multi-threaded read access should use a separate H5Dataspace for each thread
 * (otherwise one thread can override the elements selected by another thread).
 *
 * In the 'read to' case, the H5DataSpace represents a 'memory space'. It's a HDF5 handle that
 * describes how many elements you intend to read.
 *
 * There is no support yet for reading datasets that are comprised of multiple chunks (i.e.
 * non-contiguous datasets).
 */
public class H5DataSpace extends H5Object {

  /**
   * The underlying file-based dataset, or null if this is a memory-space
   */
  private final H5Dataset dataset;

  @Getter
  private final long[] extent;

  /**
   * Creates a dataspace handle suitable to use as a 'memory space' in other HDF5 library calls. In
   * HDF5 library terms, a memory-space handle is much the same as a data-space handle. For
   * memory-spaces we just use a 'simple' dataspace that's big enough to hold the elements we're
   * interested in. Whereas for file-based dataspaces (what we read *from*), we use
   * {@link H5Dataset#newDataSpace()} to get a handle that relates to the underlying file-based
   * dataset. See also {@link H5#H5Screate_simple(int, long[], long[])} method.
   *
   * @param dims an array of the dimensions, where the nth index gives the size of the nth dimension.
   *             To create a 1d memory space that can hold two elements, call `createSimple(new long[]
   *             {2})`. To create a 10x10 dataspace, call `createSimple(new long[] {10, 10})`
   * @return a reference to the dataspace - it is your responsibility to close it when you're done
   */
  public static H5DataSpace createMemSpace(long[] dims) {
    return new H5DataSpace(H5.H5Screate_simple(dims.length, dims, null), null, dims);
  }

  /**
   * Returns a memory space suitable to use for reading the numElements specified from a
   * one-dimensional dataset. Refer {@link #createMemSpace(long[]).
   *
   * @return an H5DataSpace - it is your responsibility to close it when you're done
   */
  public static H5DataSpace createMemSpace(long numElements) {
    return createMemSpace(new long[] {numElements});
  }

  private static long[] readH5Dimensions(long ptr) {
    long[] dims = new long[H5Sget_simple_extent_ndims(ptr)];
    H5.H5Sget_simple_extent_dims(ptr, dims, null);
    return dims;
  }

  public H5DataSpace(long id, H5Dataset dataset) {
    // compute the extent of the dataspace once, as it shouldn't change and is expensive
    this(id, dataset, readH5Dimensions(id));
  }

  public H5DataSpace(long id, H5Dataset parentDataset, long[] dims) {
    super(id);
    this.dataset = parentDataset;
    this.extent = dims;
  }

  /**
   * @return the total number of elements in the dataset, by totalling
   * up the extent (fixed size) for each of the dataset's dimensions
   */
  public long numElements() {
    long counter = 0;
    for (int i = 0; i < extent.length; i++) {
      if (counter == 0) {
        /* for first dimension, just use the size */
        counter = extent[i];
      } else if (extent[i] != 0) {
        /* then multiply that by any subsequent (non-zero) dimensions */
        counter *= extent[i];
      }
    }
    return counter;
  }

  /**
   * Same as numElements() but should only be used when you're certain that
   * the number of elements in the dataset will not overflow an integer value.
   */
  public int numElementsAsInt() {
    long numElements = numElements();
    if (numElements > Integer.MAX_VALUE) {
      throw new IllegalStateException("Dataset too big to store as integer");
    }
    return (int)numElements;
  }

  /**
   * Selects a hyperslab of elements within the dataspace,
   * using the starting position and number of elements specified.
   *
   * Clears any previous selection
   *
   */
  public void selectElements(long[] start, long[] count) {
    /* setting stride to one in all dimensions means select every element */
    long[] stride = new long[numDimensions()];
    Arrays.fill(stride, 1);

    H5.H5Sselect_hyperslab(ptr, HDF5Constants.H5S_SELECT_SET, start,
        stride, count, null /* block */);
  }

  /**
   * Select specific elements from arbitrary locations from the dataset by specifying them as points within the n
   * dimensional dataset.  If the dataset is a 1d list, then you can select the 0th, 5th and 1st elements with
   * `selectElementsAt(new long[] {{0}, {5}, {1}})`. If the dataset is a 10x10x10 cube, then you could select some of
   * the corners with `selectElementsAt(new long[][] {{0, 0, 0}, {0, 9, 0}, {9, 9 9}})`
   *
   * Clears any previous selection
   *
   * @param locations a list of coordinates to select
   */
  public void selectElementsAt(long[][] locations) {
    H5.H5Sselect_elements(ptr, HDF5Constants.H5S_SELECT_SET, locations.length, locations);
  }

  /**
   * Reads the specified elements from a one-dimensional dataset.
   *
   * @param start the index of the first element to read
   * @param count the number of elements to read
   * @return a ByteBuffer containing the data read
   */
  public ByteBuffer readElements(long start, long count) {
    return readElements(new long[] {start}, new long[] {count});
  }

  /**
   * Reads the specified elements from a dataset.
   *
   * For example given a two dimensional dataset`readElements(new long[] {2, 4}, new long[] {10, 1})`
   * would return 10 items made up of the the fifth item on the second dimension, for the 3rd - 13th
   * items on the primary dimension.
   *
   * @param start the index of the first element to read for each dimension
   * @param count the number of elements to read for each dimension
   * @return a ByteBuffer containing the data read
   */
  public ByteBuffer readElements(long[] start, long[] count) {
    // a memoryspace that *exactly* matches the size being read is required
    try (H5DataSpace memspace = H5DataSpace.createMemSpace(count)) {

      // allocate bytes to populate based on size
      long totalCount = Arrays.stream(count).reduce(1, (l, r) -> l * r);
      long bytesNeeded = totalCount * dataset.getDataType().getDataSize();
      byte[] byteArray = new byte[(int) bytesNeeded];

      // setup the dataspace so the elements we want to read are selected
      selectElements(start, count);

      H5.H5Dread(dataset.getPointer(),
          dataset.getDataType().getPointer(),
          memspace.getPointer(),
          this.getPointer(),
          HDF5Constants.H5P_DEFAULT,
          byteArray);

      // wrap up the data read in a ByteBuffer for easy access
      ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
      byteBuffer.order(ByteOrder.nativeOrder());
      return byteBuffer;
    }
  }

  public int numDimensions() {
    return getExtent().length;
  }

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