/*
 * 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 java.nio.ByteBuffer;
import java.util.AbstractList;
import java.util.HashMap;

import lombok.Getter;

import nz.org.riskscape.hdf5.types.H5ArrayType;
import nz.org.riskscape.hdf5.H5CompoundMember;
import nz.org.riskscape.hdf5.types.H5CompoundType;
import nz.org.riskscape.hdf5.H5DataSpace;
import nz.org.riskscape.hdf5.H5Dataset;
import nz.org.riskscape.hdf5.types.H5IntegerType;

/**
 * A list of {@link GmfData} objects that is backed by the hdf5 dataset. Traversing the list will
 * give you all the shaking data associated with a given site.
 */
public class GmfDataBySiteIdList extends AbstractList<GmfData> {

  /**
   * The site id we are accessing - mostly here for debugging output
   */
  @Getter
  private final long siteId;

  /**
   * The start elements from the gmf data indices dataset that locates the start of ranges of data within gmf data that
   * we read gmv values from for this site.  Used to select only the elements we need from the dataspace
   */
  private final long[] startIndices;
  /**
   * The end elements from the gmf data indices dataset that locates the end of ranges of data within gmf data that we
   * read gmv values from for this site.  Used to select only the elements we need from the dataspace.  Zips up with
   * startIndices to form an inclusive-exclusive range
   */
  private final long[] endIndices;

  /**
   * Total number of {@link GmfData} elements in this list - not that we'll ever hold this many at once
   */
  private final int size;

  /**
   * The underlying dataset we read the gmf values from
   */
  private final H5Dataset gmfDataset;

  // memoized members to make data access quicker
  private final H5CompoundMember sidMember;
  private final H5CompoundMember eidMember;
  private final H5CompoundMember gmvMember;

  // TODO replace this with a big, single byte buffer and read from it contiguously
  private final HashMap<Long, ByteBuffer> cachedBytes = new HashMap<>();

  public GmfDataBySiteIdList(long siteId, long[] startIndices, long[] endIndices, H5Dataset gmfDataset) {
    this.siteId = siteId;
    this.startIndices = startIndices;
    this.endIndices = endIndices;
    this.gmfDataset = gmfDataset;
    this.size = calculateSize();

    H5CompoundType type = (H5CompoundType) gmfDataset.getDataType();
    sidMember = type.findMember("sid");
    ((H5IntegerType)sidMember.type).setOpaqueUnsignedLongs(true);
    eidMember = type.findMember("eid");
    ((H5IntegerType)eidMember.type).setOpaqueUnsignedLongs(true);
    gmvMember = type.findMember("gmv");
  }

  public GmfDataBySiteIdList(long siteid, long[][] indices, H5Dataset gmfDataset) {
    this(siteid, indices[0], indices[1], gmfDataset);
  }

  public GmfDataBySiteIdList(long siteid, SitecolGmfDataIndex index, H5Dataset gmfDataset) {
    this(siteid, index.lookupIndices(siteid), gmfDataset);
  }

  private int calculateSize() {
    int total = 0;
    for (int i = 0; i < endIndices.length; i++) {
      long start = startIndices[i];
      long end = endIndices[i];

      total += end - start;
    }

    return total;
  }

  @Override
  public GmfData get(int index) {
    int total = 0;
    long start = -1;
    long end = -1;
    for (int i = 0; i < endIndices.length; i++) {
      start = startIndices[i];
      end = endIndices[i];

      if (index >= total && index < total + (end - start)) {
        break;
      }
      total += end - start;
    }

    ByteBuffer buffer = readFrom(start, end);
    int selectionOffset = index - total; // location within range
    int byteOffset = (int) (gmfDataset.getDataType().getDataSize() * selectionOffset);

    long sid = ((Number) sidMember.read(buffer, byteOffset)).longValue();
    long eid = ((Number) eidMember.read(buffer, byteOffset)).longValue();
    float[] floats = ((H5ArrayType) gmvMember.type).readFloats(buffer, gmvMember.byteOffset + byteOffset);

    return new GmfData(eid, sid, floats);
  }

  private void populateCachedBytes() {
    // populate our cached GmfData if this is the first time we're reading it
    if (cachedBytes.isEmpty()) {

      // we do all the reading up front in one go for performance. The HDF5 APIs are
      // wrapped in one global lock. As there may be hundreds of API calls needed to read
      // all the GMF data for one site, it can reduce lock contention significantly.
      // However, it comes with extra memory overhead, as we hold all the shaking data
      // associated with a site in memory at once.
      synchronized (gmfDataset) {
        H5DataSpace dataspace = gmfDataset.newDataSpace();

        for (int i = 0; i < endIndices.length; i++) {
          long start = startIndices[i];
          long end = endIndices[i];

          cachedBytes.put(start, dataspace.readElements(start, end - start));
        }
        dataspace.close();
      }
    }
  }

  // return a byte buffer that maps to the given start and end index.
  private ByteBuffer readFrom(long start, long end) {
    populateCachedBytes();
    return cachedBytes.get(start);
  }

  @Override
  public int size() {
    return size;
  }

  @Override
  public String toString() {
    return String.format("GmfDataBySiteId(List, siteid=%d, size=%d)", siteId, size);
  }
}
