/*
 * 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.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.cli.EngineOnlyCommand;
import nz.org.riskscape.engine.cli.StubCommand;
import nz.org.riskscape.engine.cli.Table;
import nz.org.riskscape.engine.cli.Table.Property;
import nz.org.riskscape.picocli.CommandLine.Command;
import nz.org.riskscape.picocli.CommandLine.Parameters;

@Command(
    name="hdf5",
    subcommands= {
        Hdf5Command.LsCommand.class
    }
)
public class Hdf5Command extends StubCommand {

  @Command(name="ls")
  public static class LsCommand extends EngineOnlyCommand {

    @Parameters(arity="1", index="0")
    public Path hdf5File;

    @Parameters(arity="0..1", index="1")
    public String location;

    @Override
    public Object doCommand(Engine useEngine) {
      try (H5File h5file = new H5File(hdf5File)) {
        if (location == null) {
          location = "/";
        }

        H5Object opened;
        try {
          opened = h5file.openObject(location);
        } catch (RuntimeException e) {
          printerr("Failed to open object %s  - %s", location, e.toString());
          e.printStackTrace(stderr());
          return null;
        }

        List<H5Object> children = new ArrayList<>();

        if (opened instanceof H5Group) {
          H5Group group = (H5Group) opened;
          group.visit((parent, childName, supplier) -> {
            try {
              children.add(supplier.get());
            } catch (RuntimeException e) {
              printerr("Failed to open object %s/%s  - %s", location, childName, e.toString());
              e.printStackTrace(stderr());
            }
          });
        }
        if (opened instanceof H5Dataset) {
          children.add(opened);
        }

        Table table = Table.fromList(children, H5Object.class, getMessages().getLabels(), Arrays.asList(
          Property.of("name", obj -> getName(obj)),
          Property.of("type", obj -> getType(obj)),
          Property.of("size", obj -> getSize(obj))
        ));

        // we print the table ourselves instead of closing it so we can explicitly clean up all the h5 objects *after*
        // we convert everything to a table
        table.print(getTerminal());

        for (H5Object h5Object : children) {
          h5Object.close();
        }
      }

      return null;
    }

    private String getSize(H5Object obj) {
      if (obj instanceof H5Group) {
        H5Group group = (H5Group) obj;
        AtomicLong counter = new AtomicLong(0);
        group.visit((a, b, c) -> {
          counter.incrementAndGet();
        });
        return counter.toString();
      } else {
        H5Dataset dataset = (H5Dataset) obj;
        long total = 1;
        StringBuilder builder = new StringBuilder();
        long[] extent = dataset.getDataSpace().getExtent();
        boolean first = true;
        for (long dimSize : extent) {
          if (!first) {
            builder.append("x");
          }
          builder.append(dimSize);
          first = false;
          total = total * dimSize;
        }

        if (extent.length > 1) {
          builder.append(" (Total size: ").append(total).append(")");
        }
        return builder.toString();
      }
    }

    private String getType(H5Object obj) {
      if (obj instanceof H5Group) {
        return "(Group)";
      } else {
        H5Dataset dataset = (H5Dataset) obj;
        return dataset.getDataType().toString();
      }
    }

    public String getName(H5Object obj) {
      if (obj instanceof H5Group) {
        return ((H5Group) obj).getGroupName();
      } else {
        return ((H5Dataset) obj).getDatasetName();
      }
    }
  }
}
