/*
 * 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 it.geosolutions.imageio.plugins.arcgrid.raster;

import static org.junit.Assert.*;

import java.awt.geom.Point2D;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;

import javax.media.jai.PlanarImage;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.gce.arcgrid.ArcGridReader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.geotools.api.parameter.GeneralParameterValue;

import nz.org.riskscape.engine.DefaultEngine;
import nz.org.riskscape.engine.Engine;
import nz.org.riskscape.engine.TemporaryDirectoryTestHelper;
import nz.org.riskscape.engine.data.coverage.CoverageFileBookmarkResolver;

public class AsciiGridRasterTest implements TemporaryDirectoryTestHelper {

  // needs to be big enough to trigger use of tiles in underlying java imageio code - these
  // values seem reasonable?
  private final int width = 1000;
  private final int height = 1000;

  private Path tmpDir;
  private String path;

  Engine engine = new DefaultEngine();
  CoverageFileBookmarkResolver resolver = new CoverageFileBookmarkResolver(engine);

  @Before
  public void createRaster() throws IOException {
    tmpDir = createTempDirectory("AsciiGridRasterTest");

    File tempFile = File.createTempFile("grid-test", ".asc", tmpDir.toFile());
    path  = tempFile.getAbsolutePath();
    PrintStream out = new PrintStream(path);
    out.format("ncols %d\n", width);
    out.format("nrows %d\n", height);
    out.format("xllcorner 0\n");
    out.format("yllcorner 0\n");
    out.format("cellsize 1\n");

    int counter = 0;
    for (int x = 0; x < width; x++) {
      for (int y = 0; y < height; y++) {
        out.format("%d ", counter);
        counter++;
      }

      out.println("");
    }

    out.close();
  }

  @After
  public void teardown() throws Exception {
    remove(tmpDir);
  }

  @Test
  public void canSamplePixelsFromGridInSequence() throws Exception {
    GridCoverage2D grid = open();
    PlanarImage image = (PlanarImage) grid.getRenderedImage();

    int tileHeight = image.getTileHeight();
    if (tileHeight != image.getHeight() && image.getWidth() == image.getTileWidth()) {
      // we access every single pixel in the raster in the order it was written (and so the order on disk)
      // and check it has the assigned value
      final int numPixels = width * height;
      int pixelCount = 0;
      while (pixelCount < numPixels) {
        assertPixelValue(grid, pixelCount, pointFromExpectedPixelValue(pixelCount));
        pixelCount++;
      }
    } else {
      fail("image tiling not as expected");
    }
  }

  private GridCoverage2D open() throws Exception {
    return new ArcGridReader(new File(path)).read(new GeneralParameterValue[0]);
  }

  @Test
  public void canSamplePixelsFromGridWithGapsBetweenUnderlyingImageTiles() throws Exception {
    GridCoverage2D grid = open();
    PlanarImage image = (PlanarImage) grid.getRenderedImage();

    int tileHeight = image.getTileHeight();
    if (tileHeight != image.getHeight() && image.getWidth() == image.getTileWidth()) {

      // regression test - there was a bug where indexes in to the file were cached, but those values
      // were used inappropriately, resulting in an off by one error
      int pixelsBetweenTiles = width * tileHeight * 2;

      int[] values = new int[] {1001, 1001 + pixelsBetweenTiles};

      for (int value : values) {
        assertPixelValue(grid, value, pointFromExpectedPixelValue(value));
      }
    } else {
      fail("image tiling not as expected");
    }
  }

  // because grid dimensions are 1-to-1 with the bitmap (apart from y axis reversal) and the bitmap
  // is a sequence of increasing integers, we can build a point from an expected value.
  private Point2D pointFromExpectedPixelValue(int expectedValue) {
    int x = expectedValue % width;
    // y axis is reversed
    int y = height - (expectedValue / height);
    return new Point2D.Double(x, y);
  }

  private void assertPixelValue(GridCoverage2D grid, int expected, Point2D point) {
    int[] valueStore = new int[] {-1};
    grid.evaluate(point, valueStore);
    assertEquals(expected, valueStore[0]);
  }
}
