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

import nz.org.riskscape.hdf5.types.H5Type;

import java.nio.ByteBuffer;

import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.hdf5.H5CompoundMember;

import lombok.Getter;

import nz.org.riskscape.hdf5.H5DataSpace;
import nz.org.riskscape.hdf5.H5Dataset;

/**
 * Iterates over elements of an {@link H5Dataset}
 */
public class H5FixedSizeCursor extends H5DatasetCursor {

  @Getter
  private ByteBuffer byteBuffer;
  @Getter
  private long currentIndex = 0;
  /**
   * The offset (in number of elements) into byte buffer that the current index is. This will need
   * to by multiplied by {@link #elementSizeBytes} to become a byte offset into that buffer.
   */
  private int elementOffset = 0;


  private final int elementSizeBytes;

  private final int maxElementsPerRead;

  public H5FixedSizeCursor(H5Dataset dataset, H5DataSpace ds, H5Type type, int cursorBufferSize) {
    super(dataset, ds, type);

    elementSizeBytes =  (int) type.getDataSize();

    if (ds.numDimensions() > 1) {
      long requiredSizeBytes = ds.numElements() * type.getDataSize();
      if (requiredSizeBytes > cursorBufferSize) {
        throw new RiskscapeException(PROBLEMS.readSizeTooSmallForMultiDimensionedData(
            requiredSizeBytes, cursorBufferSize));
      }
      // doing a partial read of a mult-dimensional data set is a little tricky. So we take the easy option
      // and read it all at once.
      maxElementsPerRead = ds.numElementsAsInt();
    } else {
      // to handle datasets that are really large, work out a smaller size buffer
      // to use, so we avoid unnecessary memory pressure. Trim the buffer so that
      // it fits an exact number of elements
      maxElementsPerRead = cursorBufferSize / elementSizeBytes;
    }

    readElements();
  }

  @Override
  public boolean hasNext() {
    return currentIndex < numElements;
  }

  public void rewind() {
    setCurrentIndex(0);
  }

  /**
   * @return the current position in the byteBuffer (rather than the current
   * position in the overall dataset)
   * Note the only guarantee here is that you can read the next element out of
   * the byteBuffer. Reading any further than that is not supported.
   */
  private int position() {
    return elementOffset * elementSizeBytes;
  }

  @Override
  public void setCurrentIndex(long index) {
    int newElementOffset = elementOffset + (int)(index - currentIndex);

    currentIndex = index;
    if (0 > newElementOffset || newElementOffset >= maxElementsPerRead) {
      // The desired index is not in the current buffer, we need to read
      readElements();
    } else {
      elementOffset = newElementOffset;
    }
  }

  private void incrementPosition() {
    setCurrentIndex(currentIndex + 1);
  }

  @Override
  public Object next() {
    Object read = peek();
    incrementPosition();
    return read;
  }

  @Override
  public Object peek() {
    return  type.read(byteBuffer, position());
  }

  @Override
  public Object peek(H5CompoundMember member) {
    return member.read(byteBuffer, position());
  }

  @Override
  public void skip() {
    incrementPosition();
  }

  /* Read elements out of the file dataspace and into our byteBuffer */
  private void readElements() {
    if (dataspace.numDimensions() > 1) {
      // doing a partial read of a mult-dimensional data set is a little tricky. So we take the easy option
      // and read it all at once.
      long[] dimStart = new long[dataspace.numDimensions()];
      long[] dimCount = new long[dataspace.numDimensions()];
      for (int i = 0; i < dataspace.numDimensions(); i++) {
        dimStart[i] = 0;
        dimCount[i] = dataspace.getExtent()[i];
      }
      byteBuffer = dataspace.readElements(dimStart, dimCount);
    } else {
      long elementsToRead = Math.min(maxElementsPerRead, numElements - currentIndex);
      if (elementsToRead > 0) {
        // we don't want to try to read past the end
        byteBuffer = dataspace.readElements(currentIndex, elementsToRead);
      }
    }
    elementOffset = 0;
  }
}
