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

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Base class for {@link Resource}s.
 */
@RequiredArgsConstructor @EqualsAndHashCode
public abstract class BaseResource implements Resource {

  @Getter
  protected final URI location;

  @Override
  public ResultOrProblems<Path> ensureLocal(Options options, String extension) {
    try {
      // we make a temp dir just for this file as that lets us save the file with it's
      // own name which is far better that a temp file variant of it.
      Path tempDir;
      if (options.tempDirectory.isPresent()) {
        tempDir = Files.createTempDirectory(options.tempDirectory.get(), getClass().getSimpleName());
      } else {
        // XXX ideally we'd have a way to get the engines temp dir here. or require the temp dir to exist
        // in the options
        // we need a temp directory. ideally this would be provided in the options but if not we need
        // to fall back to the system default.
        tempDir = Files.createTempDirectory(getClass().getSimpleName());
      }
      String filename =
          ensureExtension(localFilename(location), extension);
      Path tempResource = tempDir.resolve(filename);
      try (InputStream is = getContentStream()) {
        Files.copy(is, tempResource);
      }
      return ResultOrProblems.of(tempResource);
    } catch (IOException e) {
      throw new RiskscapeIOException(Problems.caught(e));
    }
  }

  private String ensureExtension(String localFilename, String extension) {
    if (extension == null) {
      return localFilename;
    } else {
      String suffix;
      if (extension.equals("")) {
        // empty string means remove
        suffix = "";
      } else if (extension.startsWith(".")) {
        suffix = extension;
      } else {
        suffix = "." + extension;
      }

      int dotIndex = localFilename.indexOf('.');
      if (dotIndex == -1) {
        // case: no extension
        return localFilename + suffix;
      } else {
        // case: replace existing extension
        // - why not just tack on an extra extension?  It confuses python imports - we could put a special case in
        // the python code, but this seems fairly safe and keeps the fix in one spot.
        return localFilename.substring(0, dotIndex) + suffix;
      }
    }
  }

  protected String localFilename(URI uri) {
    String path = uri.getPath();
    if (path != null) {
      if (!path.endsWith("/")) {
        int lastSlash = path.lastIndexOf("/");
        if (lastSlash > -1) {
          return path.substring(lastSlash + 1);
        }
        return path;
      }
    }

    return "resource";
  }

}
