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

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.imageio.stream.FileImageInputStream;

import org.hamcrest.Matcher;
import org.junit.Test;

public class SparseTIFFImageReaderTest {

  /*
   * This test is here to check that the isEmptyTile method works properly, but also does some sanity checks that
   * the sampling still works
   */

  SparseTIFFImageReaderSpi imageReaderSpi = new SparseTIFFImageReaderSpi();
  SparseTIFFImageReader imageReader;

  Path testResources = Paths.get("src/test/resources", getClass().getPackageName().replace(".", "/"));

  // This is the getting started 10m tiff - as it was given to us.  It is striped, rather than tiled
  File originalTiff = new File("../../examples/getting-started/MaxEnv_All_Scenarios_10m.tif");

  // converted with SPARSE_OK and TILED
  File sparseTiff = testResources.resolve("MaxEnv_All_Scenarios_10m_sparse.tif").toFile();

  // converted with TILED - now 256^2 tiles, instead of 65536x1 stripes
  File tiledTiff = testResources.resolve("MaxEnv_All_Scenarios_10m_tiled.tif").toFile();

  // This is the original but with no-data metadata removed
  File rmNoDataTiff = testResources.resolve("MaxEnv_All_Scenarios_10m_rm-nodata.tif").toFile();

  // taken from https://github.com/geosolutions-it/imageio-ext - it is untiled and uncompressed.  I tried to generate
  // a smaller tile from the example tiff, but couldn't get the gdal incantation correct
  File imageIoTestTiff = testResources.resolve("imageio-ext-test.tif").toFile();

  public SparseTIFFImageReaderTest() throws IOException {
    imageReader = (SparseTIFFImageReader) imageReaderSpi.createReaderInstance();
  }

  @Test
  public void sparseTest() throws IOException {
    setInput(sparseTiff);

    assertThat(imageReader.hasEmptyTiles(), is(true));
    assertThat(imageReader.isEmptyTile(0, 0), is(true));

    BufferedImage tile = imageReader.readTile(0, 0, 0);
    DataBuffer dataBuffer = tile.getRaster().getDataBuffer();

    // check a no data tile
    for (int i = 0; i < dataBuffer.getSize(); i++) {
      assertThat(dataBuffer.getElemDouble(i), is(-99999D));
    }

    // check a well-known pixel
    int tileXWithData = 6520 / 256;
    assertThat(imageReader.isEmptyTile(tileXWithData, 0), is(false));
    tile = imageReader.readTile(0, tileXWithData, 0);
    dataBuffer = tile.getRaster().getDataBuffer();

    assertThat(dataBuffer.getElemDouble(6520 - (tileXWithData * 256)), isWellKnownPixelValue());
  }

  @Test
  public void nonSparseTest() throws Exception {
    setInput(tiledTiff);

    assertThat(imageReader.hasEmptyTiles(), is(true));
    assertThat(imageReader.isEmptyTile(0, 0), is(true));

    BufferedImage tile = imageReader.readTile(0, 0, 0);
    DataBuffer dataBuffer = tile.getRaster().getDataBuffer();

    for (int i = 0; i < dataBuffer.getSize(); i++) {
      assertThat(dataBuffer.getElemDouble(i), is(-99999D));
    }

    // check a well-known pixel
    int tileXWithData = 6520 / 256;
    assertThat(imageReader.isEmptyTile(tileXWithData, 0), is(false));
    tile = imageReader.readTile(0, tileXWithData, 0);
    dataBuffer = tile.getRaster().getDataBuffer();

    assertThat(dataBuffer.getElemDouble(6520 - (tileXWithData * 256)), isWellKnownPixelValue());
  }

  @Test
  public void stripedTiffsAlsoWork() throws Exception {
    setInput(originalTiff);

    // there are no empty tiles in this tiff, not because it's striped, but because each strip contains data
    assertThat(imageReader.hasEmptyTiles(), is(false));
    assertThat(imageReader.isEmptyTile(0, 0), is(false));

    BufferedImage tile = imageReader.readTile(0, 0, 0);
    DataBuffer dataBuffer = tile.getRaster().getDataBuffer();

    // the top left pixel is no-data, but the first stripe does have data elsewhere
    assertThat(dataBuffer.getElemDouble(0), is(-99999D));

    // taken from qgis
    assertThat(dataBuffer.getElemDouble(6520), isWellKnownPixelValue());
  }

  @Test
  public void worksWhenNoDataMissing() throws Exception {
    setInput(rmNoDataTiff);

    assertThat(imageReader.hasEmptyTiles(), is(false));
    assertThat(imageReader.isEmptyTile(0, 0), is(false));

    BufferedImage tile = imageReader.readTile(0, 0, 0);
    DataBuffer dataBuffer = tile.getRaster().getDataBuffer();

    // the top left pixel is still our no-data value, just that the tiff doesn't declare this to be so.
    assertThat(dataBuffer.getElemDouble(0), is(-99999D));

    // taken from qgis
    assertThat(dataBuffer.getElemDouble(6520), isWellKnownPixelValue());
  }

  @Test
  public void worksWithUncompressedUntiledTif() throws Exception {
    // this is here really as a sanity check that nothing bad happens if one of these gets read by our custom tiff
    // reader
    setInput(imageIoTestTiff);

    assertThat(imageReader.hasEmptyTiles(), is(false));
    assertThat(imageReader.isEmptyTile(0, 0), is(false));

    BufferedImage tile = imageReader.readTile(0, 0, 0);
    DataBuffer dataBuffer = tile.getRaster().getDataBuffer();

    // a couple of pixels from qgis
    assertThat(dataBuffer.getElemDouble(0), equalTo(0D));
    assertThat(dataBuffer.getElemDouble(5), equalTo(192D));
  }

  // This is a value I picked from qgis - we assert it is the same in all versions of the tiff
  private Matcher<Double> isWellKnownPixelValue() {
    return closeTo(1.385136D, 0.000001);
  }

  private void setInput(File file) throws FileNotFoundException, IOException {
    imageReader.setInput(new FileImageInputStream(file));

    // normally the coverage would do this, but here we have to instead
    imageReader.initialize(0);
  }
}
