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

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

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.RelationMatchers;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.data.Bookmark;
import nz.org.riskscape.engine.data.ResolvedBookmark;
import nz.org.riskscape.engine.defaults.resource.HttpResourceLoader;
import nz.org.riskscape.engine.relation.Relation;
import nz.org.riskscape.engine.resource.ResourceProblems;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;


public class NetCDFResolverTest extends ProjectTest {

  NetCDFResolver resolver = new NetCDFResolver(engine);
  Relation relation;

  @Before
  public void setup() throws Exception {
    engine.getResourceFactory().add(new HttpResourceLoader(engine));
  }

  @Test
  public void canReadInts() {
    read("INTS");

    Struct expected = Struct.of("INTS", Types.INTEGER);
    assertThat(relation.getType(), is(expected));

    assertThat(relation, RelationMatchers.relationWithTuples(
        Tuple.ofValues(expected, 22L),
        Tuple.ofValues(expected, 33L)
    ));
  }

  @Test
  public void canReadDoubles() {
    read("DOUBLES");

    Struct expected = Struct.of("DOUBLES", Types.FLOATING);
    assertThat(relation.getType(), is(expected));

    assertThat(relation, RelationMatchers.relationWithTuples(
        Tuple.ofValues(expected, 0.5D),
        Tuple.ofValues(expected, 0.7D)
    ));
  }

  @Test
  public void canReadFloats() {
    read("FLOATS");

    Struct expected = Struct.of("FLOATS", Types.FLOATING);
    assertThat(relation.getType(), is(expected));

    List<Double> floats = new ArrayList<>();
    relation.iterator().forEachRemaining(t -> floats.add((Double)Types.FLOATING.coerce(t.fetch("FLOATS"))));
    assertThat(floats, contains(
        closeTo(0.4D, 0.001D),
        closeTo(0.6D, 0.001D)
    ));
  }

  @Test
  public void canReadShorts() {
    read("SHORTS");

    Struct expected = Struct.of("SHORTS", Types.INTEGER);
    assertThat(relation.getType(), is(expected));

    assertThat(relation, RelationMatchers.relationWithTuples(
        Tuple.ofValues(expected, 10L),
        Tuple.ofValues(expected, 20L)
    ));
  }

  @Test
  public void canReadBytes() {
    read("BYTES");

    Struct expected = Struct.of("BYTES", Types.INTEGER);
    assertThat(relation.getType(), is(expected));

    assertThat(relation, RelationMatchers.relationWithTuples(
        Tuple.ofValues(expected, 1L),
        Tuple.ofValues(expected, 2L)
    ));
  }

  @Test
  public void canReadData() {
    read("DATA");

    Struct expected = Struct.of("BYTES", Types.INTEGER, "DATA", Types.INTEGER);
    assertThat(relation.getType(), is(expected));


    assertThat(relation, RelationMatchers.relationWithTuples(
        Tuple.ofValues(expected, 1L, 43L),
        Tuple.ofValues(expected, 2L, 55L)
    ));
  }

  @Test
  public void giveGoodErrorOnMissingRemoteFile() {
    URI target = URI.create("https://riskscape.org.nz/bogus/test.nc");
    Bookmark bookmark = new Bookmark("test", "my test bookmark", "netcdf",
        target,
        ImmutableMap.of("layer", Arrays.asList("test")));

    assertThat(
        resolver.resolve(bookmark, executionContext).get().getData(Relation.class),
        Matchers.failedResult(
            Matchers.hasAncestorProblem(is(ResourceProblems.get().notFound(target)))
        )
    );
  }

  private void read(String layer) {
    Bookmark bookmark = new Bookmark("test", "my test bookmark", "netcdf", testUri("test.nc"),
        ImmutableMap.of("layer", Arrays.asList(layer)));

    ResolvedBookmark resolved = resolver.resolve(bookmark, executionContext).get();
    relation = resolved.getData(Relation.class).get();
  }

  protected URI testUri(String string) {
    try {
      return getClass().getResource("/nz/org/riskscape/netcdf/" + string).toURI();
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }


}
