/*
 * 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 nz.org.riskscape.hdf5.types.H5Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;

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

import hdf.hdf5lib.H5;
import hdf.hdf5lib.HDF5Constants;
import hdf.hdf5lib.exceptions.HDF5Exception;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.engine.types.TypeProblems;

/**
 * A metadata attribute for a dataset
 */
@EqualsAndHashCode(callSuper = false)
public class H5Attribute extends H5Object {

  @Getter
  private final String name;

  @Getter
  private final H5Type dataType;

  // the parent dataset/group/etc that contains this attribute
  private final H5Object parent;

  public H5Attribute(H5Object object, String name) {
    super(H5.H5Aopen(object.ptr, name, HDF5Constants.H5P_DEFAULT));
    this.name = name;
    this.dataType = H5Type.build(H5.H5Aget_type(ptr));
    this.parent = object;
  }

  // TODO an attribute itself can hold a multi-dimensional array of data.
  // Here, the reading assumes it'll only hold a single value
  public Object read() {
    /* first we read the raw attribute data into a byte array */
    byte[] dataBytes = new byte[(int)dataType.getDataSize()];
    H5.H5Aread(ptr, dataType.ptr, dataBytes);

    /* then we use the underlying H5Type to convert the raw data to an object */
    ByteBuffer byteBuffer = ByteBuffer.wrap(dataBytes);
    byteBuffer.order(ByteOrder.nativeOrder());
    return dataType.read(byteBuffer, 0);
  }

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

  @Override
  public String toString() {
    return "HDF5 Attribute '" + name + "'";
  }

  /**
   * Helper to read an attribute's value from a given HDF5 object (e.g. dataset).
   *
   * @return the given value that the attribute holds, cast to the expected type
   * @throws ProblemException that must be handled by caller (at some point)
   */
  public static <T> ResultOrProblems<T> readValue(H5Object object, String attributeName, Class<T> expectedType) {
    Problem missingAttribute = GeneralProblems.get().noSuchObjectExists(attributeName, H5Attribute.class);
    H5Attribute attribute;
    try {
      attribute = new H5Attribute(object, attributeName);
    } catch (HDF5Exception e) {
      return ResultOrProblems.failed(missingAttribute);
    }

    Object value;
    try {
      value = attribute.read();
    } finally {
      attribute.close();
    }

    if (value == null) {
      return ResultOrProblems.failed(missingAttribute);
    } else if (expectedType.isInstance(value)) {
      return ResultOrProblems.of(expectedType.cast(value));
    } else {
      return ResultOrProblems.failed(TypeProblems.get().mismatch(attribute, expectedType, value.getClass()));
    }
  }
}
