/*
 * 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 java.util.List;
import java.util.Optional;

import com.google.common.collect.ImmutableList;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.index.strtree.STRtree;

import lombok.extern.slf4j.Slf4j;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.relation.TupleIterator;
import nz.org.riskscape.engine.rl.ExpressionRealizer;
import nz.org.riskscape.engine.rl.RealizedExpression;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Types;
import nz.org.riskscape.rl.ast.FunctionCall;

/**
 * {@link JoinIndexer} implementation that attempts to build an in-memory spatial index of the tuples
 * for narrowing down the set of rhs tuples.
 */
@Slf4j
public class SpatialIndexer extends RealizedExpressionJoinIndexer {

  public static final Constructor CONSTRUCTOR = (join, expressionRealizer, initalIndexSize) ->
      new SpatialIndexer(join, expressionRealizer);

  public static final List<String> ALLOWED_GEO_FUNCTIONS = ImmutableList.of("contains", "intersects", "within");

  /**
   * The constructed index.  Plucked from the soft reference once built so that it won't be garbage collected.
   */
  private STRtree strTree;
  private boolean strTreeBuilt = false;

  public SpatialIndexer(Join join, TupleIterator rhs, ExpressionRealizer expressionRealizer) {
    this(join, expressionRealizer);
    while (rhs.hasNext()) {
      addToIndex(rhs.next());
    }
  }

  public SpatialIndexer(Join join, ExpressionRealizer expressionRealizer) {
    super(join, expressionRealizer);

    this.strTree = new STRtree(16);

    processIndexableMetadata();
  }

  @Override
  public boolean isUsable() {
    return this.rhsExpression != null && this.lhsExpression != null
        && Nullable.strip(lhsExpression.getResultType()) == Types.GEOMETRY
        && Nullable.strip(rhsExpression.getResultType()) == Types.GEOMETRY;
  }

  @Override
  protected boolean isAllowed(RealizedExpression childFilter) {
    if (super.isAllowed(childFilter)) {
      if (childFilter.getExpression() instanceof FunctionCall) {
        FunctionCall functionCall = (FunctionCall)childFilter.getExpression();
        return ALLOWED_GEO_FUNCTIONS.contains(functionCall.getIdentifier().getValue());
      }
    }
    return false;
  }

  @Override
  public TupleIterator createRhsIterator(Tuple lhs) {

    checkIfIndexBuilt();

    Geometry lhsGeometry = (Geometry)lhsExpression.evaluate(lhs);
    Envelope lhsEnvelope = lhsGeometry.getEnvelopeInternal();

    // now pull a list from the index and return it
    @SuppressWarnings("unchecked")
    List<Tuple> items = strTree.query(lhsEnvelope);

    if (items.isEmpty()) {
      return TupleIterator.EMPTY;
    } else if (items.size() == 1) {
      return TupleIterator.singleton(items.get(0));
    } else {
      return TupleIterator.wrapped(items.iterator(), Optional.empty());
    }
  }

  private void checkIfIndexBuilt() {
    // avoid acquiring the lock
    if (!strTreeBuilt) {
      synchronized (strTree) {
        if (!strTreeBuilt) {
          strTree.build();
          strTreeBuilt = true;
        }
      }
    }
  }

  // package level to allow test evilness
  @Override
  public void addToIndex(Tuple toCache) {
    Geometry rhsGeom = (Geometry)rhsExpression.evaluate(toCache);

    if (rhsGeom == null) {
      //Can't spatially index a null geometry.
      return;
    }

    Envelope envelopeInternal = rhsGeom.getEnvelopeInternal();
    strTree.insert(envelopeInternal, toCache);
  }

  @Override
  public String toString() {
    return getClass().getSimpleName();
  }
}
