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

import static hdf.hdf5lib.HDF5Constants.*;

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

import hdf.hdf5lib.H5;

import nz.org.riskscape.hdf5.H5DataSpace;
import nz.org.riskscape.hdf5.H5Dataset;
import nz.org.riskscape.hdf5.types.H5Type;
import nz.org.riskscape.hdf5.types.H5VlenType;

/**
 * Does the dirty work of returning a list of start/stop locations that return all the events for a particular siteid
 */
public class SitecolGmfDataIndex {

  private final H5Dataset gmfdataIndices;
  private final long memspaceId;
  private final boolean vlen;
  private final H5DataSpace dataspace;

  public SitecolGmfDataIndex(H5Dataset gmfdataIndices) {
    this.gmfdataIndices = gmfdataIndices;
    this.memspaceId = H5.H5Screate_simple(1, new long[] {2}, null);
    this.dataspace = gmfdataIndices.newDataSpace();
    // the indices dataset can take two different shapes - one is a 2d array of vlen indexes, which is what we
    // see with a probabilistic hdf5 file
    // the second is just a 2d array of indexes, which is what we see with a scenario
    this.vlen = gmfdataIndices.getDataType() instanceof H5VlenType;
  }

  public long[][] lookupIndices(long siteid) {
    long[][] selection =  new long[][] {
      {siteid, 0},
      {siteid, 1}
    };

    // multiple threads may be accessing the same index, so hold a lock while we read
    // to make sure another thread doesn't change the selection out from under us
    synchronized (dataspace) {

      H5.H5Sselect_elements(dataspace.getPointer(), H5S_SELECT_SET, 2, selection);

      if (vlen) {
        Object[] dataBytes = new Object[2];
        H5.H5DreadVL(
            gmfdataIndices.getPointer(),
            gmfdataIndices.getDataType().getPointer(),
            memspaceId,
            dataspace.getPointer(),
            H5P_DEFAULT, dataBytes
        );

        long[] startLongs = readLongs((byte[]) dataBytes[0]);
        long[] finishLongs = readLongs((byte[]) dataBytes[1]);

        return new long[][] {
          startLongs,
          finishLongs
        };
      } else {
        final int dataSize = (int) gmfdataIndices.getDataType().getDataSize();
        byte[] bytes = new byte[dataSize  * 2];
        H5.H5Dread(
          gmfdataIndices.getPointer(),
          gmfdataIndices.getDataType().getPointer(),
          memspaceId,
          dataspace.getPointer(),
          H5P_DEFAULT,
          bytes
        );

        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.nativeOrder());

        long start = ((Number)gmfdataIndices.getDataType().read(buffer, 0)).longValue();
        long stop = ((Number)gmfdataIndices.getDataType().read(buffer, dataSize)).longValue();

        return new long[][] {
          {start}, {stop}
        };
      }
    }
  }

  private long[] readLongs(byte[] bytes) {
    H5Type childType = ((H5VlenType) gmfdataIndices.getDataType()).getMemberType();
    int numElements = (int) (bytes.length / childType.getDataSize());
    long[] longs = new long[numElements];
    ByteBuffer wrapped = ByteBuffer.wrap(bytes);
    wrapped.order(ByteOrder.nativeOrder());
    int index = 0;
    for (int j = 0; j < bytes.length; j = j + (int)childType.getDataSize()) {
      // NB could read from the byte buffer directly and avoid the object allocation and extra method call... maybe
      Number read = (Number) childType.read(wrapped, j);
      longs[index++] = read.longValue();
    }
    return longs;
  }


}
