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

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.geotools.filter.text.cql2.CQLException;
import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.Streams;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;

import nz.org.riskscape.engine.CrsHelper;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.relation.SpatialMetadata;
import nz.org.riskscape.engine.relation.TupleIterator;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

public class SpatialIndexerTest extends BaseIndexerTest implements CrsHelper {

  Struct type = Types.GEOMETRY.asStruct();
  Struct lhsType = type.parent("lhs");
  Struct rhsType = type.parent("rhs");

  List<Tuple> lhsValues = new ArrayList<>();
  List<Tuple> rhsValues = new ArrayList<>();

  SpatialMetadata sm = new SpatialMetadata(nzMapGrid(), type.getMembers().get(0));
  ListRelation lhs = new ListRelation(type, lhsValues, sm);
  ListRelation rhs = new ListRelation(type, rhsValues, sm);
  Joiner join;

  GeometryFactory geometryFactory = project.getSridSet().getGeometryFactory(nzMapGrid());
  JoinCondition joinCondition;
  SpatialIndexer indexer;

  @Before
  public void setup() {
    //init the join with a cartisian join condition
    join = new Joiner(lhsType, rhsType, JoinCondition.CARTESIAN);
  }

  public void setupJoin() {
    join = join.withJoinConditon(joinCondition);
    indexer = new SpatialIndexer(join, expressionRealizer);

    if (!indexer.isUsable()) {
      //Don't populate an unusable index
      return;
    }
    for (Tuple toIndex : rhsValues) {
      indexer.addToIndex(toIndex);
    }
  }

  private Tuple tuple(Struct parentType, Geometry geom) {
    return Tuple.ofValues(parentType, Tuple.ofValues(this.type, geom));
  }

  @Test
  public void canIndexASimpleGeometricJoin() throws CQLException {
    lhsValues.add(tuple(lhsType, rect(0, 0, 10, 10)));
    lhsValues.add(tuple(lhsType, rect(2, 2, 5, 5)));
    rhsValues.add(tuple(rhsType, point(2, 2)));

    joinCondition = setupJoinCondition(toFilter("intersects(lhs.value, rhs.value)"), join.getJoinedType());
    setupJoin();

    assertTrue(indexer.isUsable());

    // only returns those within lhs's bounding box
    List<Tuple> collected = collect(indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.of(type, "value", rect(0, 0, 1, 1)))));
    assertTrue(collected.isEmpty());
  }

  @Test
  public void canIndexASimpleGeometricJoinThatHasNullGeomsInRHS() throws CQLException {
    lhsValues.add(tuple(lhsType, rect(0, 0, 10, 10)));
    lhsValues.add(tuple(lhsType, rect(2, 2, 5, 5)));
    rhsValues.add(tuple(rhsType, point(2, 2)));
    rhsValues.add(tuple(rhsType, null));

    joinCondition = setupJoinCondition(toFilter("intersects(lhs.value, rhs.value)"), join.getJoinedType());
    setupJoin();
    assertTrue(indexer.isUsable());


    // second pass only returns those within lhs's bounding box
    List<Tuple> collected = collect(indexer.createRhsIterator(
        tuple(lhsType, rect(0, 0, 1, 1))));
    assertTrue(collected.isEmpty());
  }

  @Test
  public void canNotIndexACartesianJoin() {
    joinCondition = JoinCondition.CARTESIAN;
    setupJoin();
    assertFalse(indexer.isUsable());
  }

  @Test
  public void canNotIndexABufferedJoinCondition() throws CQLException {
    joinCondition = setupJoinCondition(toFilter("dwithin(lhs.value, rhs.value, 1.0)"), join.getJoinedType());
    setupJoin();
    assertFalse(indexer.isUsable());
  }

  @Test
  public void canIndexAJoinConditionWithRhsGeometryInsideAnFunctionExpression() throws CQLException {
    // in once buffered
    rhsValues.add(tuple(rhsType, point(1, 1)));
    // not in even when buffered
    rhsValues.add(tuple(rhsType, point(7, 7)));

    joinCondition = setupJoinCondition(toFilter("intersects(lhs.value, buffer(rhs.value, 2.0))"), join.getJoinedType());

    setupJoin();
    assertTrue(indexer.isUsable());

    // first pass yields everything, ignores lhs value completely
    List<Tuple> collected;

    collected = collect(indexer.createRhsIterator(tuple(lhsType, rect(2, 2, 3, 3))));
    assertEquals(rhsValues.subList(0, 1), collected);

    collected = collect(indexer.createRhsIterator(tuple(lhsType, rect(6, 6, 7, 7))));
    assertEquals(rhsValues.subList(1, 2), collected);

    collected = collect(indexer.createRhsIterator(tuple(lhsType, rect(2, 2, 6, 6))));
    assertEquals(rhsValues, collected);
  }

  private List<Tuple> collect(TupleIterator createRhsIterator) {
    return Streams.stream(createRhsIterator).collect(Collectors.toList());
  }

  private Geometry rect(int x1, int y1, int x2, int y2) {
    return geometryFactory.createPolygon(new Coordinate[] {
      new Coordinate(x1, y1),
      new Coordinate(x2, y1),
      new Coordinate(x2, y2),
      new Coordinate(x1, y2),
      new Coordinate(x1, y1)
    });
  }

  private Geometry point(int x1, int y1) {
    return geometryFactory.createPoint(new Coordinate(x1, y1));
  }
}
