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

import java.util.ArrayList;
import java.util.List;

import nz.org.riskscape.engine.data.coverage.Dataset2D;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.hdf5.H5DatasetPath;
import nz.org.riskscape.hdf5.H5File;
import nz.org.riskscape.problem.ProblemException;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Parses multiple datasets from an USGS shake_result.hdf file and combines them
 * into a single result.
 */
public class UsgsShakeMapMultiDatasetReader extends UsgsShakeMapReader {

  private final List<String> datasetNames;

  public UsgsShakeMapMultiDatasetReader(H5File hdf5File, List<String> datasetNames) {
    super(hdf5File, datasetNames.get(0));
    this.datasetNames = datasetNames;
  }

  /**
   * Returns a single {@link Dataset2D} that can access all the data in the
   * underlying datasets.
   */
  @Override
  public ResultOrProblems<Dataset2D> getData() {
    return ProblemException.catching(() -> {
      List<Dataset2D> datasets = new ArrayList<>();
      for (String name : datasetNames) {
        datasets.add(getDataset2D(name).getOrThrow());
      }

      // sanity-check we're dealing with consistent grid sizes
      Dataset2D check = datasets.get(0);
      for (Dataset2D dataset : datasets) {
        if (dataset.getHeight() != check.getHeight() || dataset.getWidth() != check.getWidth()) {
          throw new ProblemException(UsgsProblems.get().datasetSizeMismatch());
        }
      }

      Struct struct = Struct.EMPTY_STRUCT;
      for (int i = 0; i < datasetNames.size(); i++) {
        String name = uniqueName(datasetNames.get(i), struct.getMemberKeys());
        struct = struct.add(name, datasets.get(i).getType());
      }

      return Dataset2D.combine(datasets, struct);
    });
  }

  private String uniqueName(String datasetPath, List<String> existingKeys) {
    String name = null;
    List<String> nameParts = new ArrayList<>();
    do {
      H5DatasetPath path = H5DatasetPath.parse(datasetPath);
      nameParts.add(0, path.getDatasetName());
      name = String.join("_", nameParts);
      // go backwards through the path, including the group, until we get a unique name
      datasetPath = path.getGroupName();
    } while (existingKeys.contains(name) && !datasetPath.equals("/"));

    return name;
  }
}
