/*
 * 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 java.util.ArrayList;

import hdf.hdf5lib.H5;
import hdf.hdf5lib.HDF5Constants;
import hdf.hdf5lib.callbacks.H5L_iterate_opdata_t;
import hdf.hdf5lib.callbacks.H5L_iterate_t;
import hdf.hdf5lib.exceptions.HDF5SymbolTableException;
import hdf.hdf5lib.structs.H5L_info_t;
import hdf.hdf5lib.structs.H5O_info_t;
import lombok.Getter;

/**
 * Methods for inspecting and accessing elements within an H5Group.  Groups should be constructed/accessed via
 * {@link H5File}
 *
 */
public class H5Group extends H5Object {

  /**
   * The group above this one.  Note that this isn't going to be 100% reliable right now - it might skip path elements
   * depending on how it was constructed.  Returns itself if this is the parent group
   */
  @Getter
  private final H5Group parent;

  @Getter
  private final String groupName;

  /**
   * Construct the root group.  Uses a static constructor to make its purpose clear.
   * @param ptr root group id
   */
  static H5Group getRootGroup(long ptr) {
    return new H5Group(ptr);
  }

  H5Group(H5Group parent, long ptr, String name) {
    super(ptr);
    this.groupName = name;
    this.parent = parent;
  }

  private H5Group(long ptr) {
    super(ptr);
    this.groupName = "/";
    this.parent = this;
  }

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

  @Override
  public String toString() {
    return "H5Group(" + groupName + ")";
  }

  /**
   * @return true if this group is at the root of an hdf5file, e.g. its name is "/"
   */
  public boolean isRoot() {
    return parent == this;
  }

  private static class IterateData implements H5L_iterate_opdata_t {
    // GDAL JNI says it wants this to be here, even though we're not using it
    @SuppressWarnings("unused")
    public ArrayList<?> iterdata = new ArrayList<>(0);
  }

  /**
   * Visit all the child objects (other groups and datasets) of this group using a callback
   * @param visitor callback that sees the children.
   */
  public void visit(H5GroupVisitor visitor) {
    H5L_iterate_opdata_t opData = new IterateData();

    H5L_iterate_t callback = (long parentGroupId, String childName, H5L_info_t info, H5L_iterate_opdata_t itData) -> {
      H5O_info_t objectInfo = H5.H5Oget_info_by_name(parentGroupId, childName, HDF5Constants.H5P_DEFAULT);
      if (objectInfo.type == HDF5Constants.H5O_TYPE_DATASET) {
        visitor.visit(this, childName, () -> openDataset(childName));
      }
      if (objectInfo.type == HDF5Constants.H5O_TYPE_GROUP) {
        visitor.visit(this, childName, () -> openGroup(childName));
      }
      return 0;
    };

    H5.H5Literate(ptr, HDF5Constants.H5_INDEX_NAME, HDF5Constants.H5_ITER_NATIVE, 0, callback, opData);
  }

  /**
   * Opens either a group or dataset, which is a member of this group, by its name
   */
  public H5Object openChild(String childName) {
    H5O_info_t objectInfo;
    try {
      objectInfo = H5.H5Oget_info_by_name(this.ptr, childName, HDF5Constants.H5P_DEFAULT);
    } catch (HDF5SymbolTableException e) {
      throw new RuntimeException("Could not find object " + childName + " inside group " + groupName, e);
    }
    if (objectInfo.type == HDF5Constants.H5O_TYPE_DATASET) {
      return openDataset(childName);
    }
    if (objectInfo.type == HDF5Constants.H5O_TYPE_GROUP) {
      return openGroup(childName);
    }
    return null;
  }

  private H5Group openGroup(String childName) {
    return new H5Group(this, H5.H5Gopen(ptr, childName, HDF5Constants.H5P_DEFAULT), childName);
  }

  private H5Dataset openDataset(String datasetName) {
    return new H5Dataset(H5.H5Dopen(ptr, datasetName, HDF5Constants.H5P_DEFAULT), datasetName);
  }

}
