/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2022
 * ELKI Development Team
 *
 * 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 in the hope that it will be useful,
 * but 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/>.
 */
package elki.index.tree.spatial.rstarvariants.xtree;

import java.util.ArrayList;
import java.util.List;

import elki.data.NumberVector;
import elki.database.ids.DBIDIter;
import elki.database.ids.DBIDRef;
import elki.database.ids.DBIDUtil;
import elki.database.ids.DBIDs;
import elki.database.query.distance.DistanceQuery;
import elki.database.query.distance.SpatialDistanceQuery;
import elki.database.query.knn.KNNSearcher;
import elki.database.query.range.RangeSearcher;
import elki.database.relation.Relation;
import elki.index.DynamicIndex;
import elki.index.KNNIndex;
import elki.index.RangeIndex;
import elki.index.tree.IndexTreePath;
import elki.index.tree.spatial.SpatialEntry;
import elki.index.tree.spatial.SpatialPointLeafEntry;
import elki.index.tree.spatial.rstarvariants.query.RStarTreeUtil;
import elki.logging.Logging;
import elki.persistent.PageFile;

/**
 * X-tree index.
 *
 * @author Marisa Thoma
 * @since 0.7.5
 */
public class XTreeIndex<O extends NumberVector> extends XTree implements RangeIndex<O>, KNNIndex<O>, DynamicIndex {
  private static final Logging LOG = Logging.getLogger(XTreeIndex.class);

  private Relation<O> relation;

  public XTreeIndex(Relation<O> relation, PageFile<XTreeNode> pagefile, XTreeSettings settings) {
    super(pagefile, settings);
    this.relation = relation;
  }

  protected SpatialEntry createNewLeafEntry(DBIDRef id) {
    return new SpatialPointLeafEntry(DBIDUtil.deref(id), relation.get(id));
  }

  @Override
  public void initialize() {
    super.initialize();
    insertAll(relation.getDBIDs()); // Will check for actual bulk load!
  }

  @Override
  public final void insert(DBIDRef id) {
    insertLeaf(createNewLeafEntry(id));
  }

  @Override
  public final void insertAll(DBIDs ids) {
    if(ids.isEmpty() || (ids.size() == 1)) {
      return;
    }

    // Make an example leaf
    if(canBulkLoad()) {
      List<SpatialEntry> leafs = new ArrayList<>(ids.size());
      for(DBIDIter id = ids.iter(); id.valid(); id.advance()) {
        leafs.add(createNewLeafEntry(id));
      }
      bulkLoad(leafs);
    }
    else {
      for(DBIDIter id = ids.iter(); id.valid(); id.advance()) {
        insert(id);
      }
    }

    doExtraIntegrityChecks();
  }

  @Override
  public final boolean delete(DBIDRef id) {
    // find the leaf node containing o
    O obj = relation.get(id);
    IndexTreePath<SpatialEntry> deletionPath = findPathToObject(getRootPath(), obj, id);
    if(deletionPath == null) {
      return false;
    }
    deletePath(deletionPath);
    return true;
  }

  @Override
  public void deleteAll(DBIDs ids) {
    for(DBIDIter id = ids.iter(); id.valid(); id.advance()) {
      delete(id);
    }
  }

  @Override
  public KNNSearcher<O> kNNByObject(DistanceQuery<O> distanceQuery, int maxk, int flags) {
    // Can we support this distance function - spatial distances only!
    return distanceQuery.getRelation() == relation && distanceQuery instanceof SpatialDistanceQuery ? //
        RStarTreeUtil.getKNNQuery(this, (SpatialDistanceQuery<O>) distanceQuery, maxk, flags) : null;
  }

  @Override
  public RangeSearcher<O> rangeByObject(DistanceQuery<O> distanceQuery, double maxradius, int flags) {
    // Can we support this distance function - spatial distances only!
    return distanceQuery.getRelation() == relation && distanceQuery instanceof SpatialDistanceQuery ? //
        RStarTreeUtil.getRangeQuery(this, (SpatialDistanceQuery<O>) distanceQuery, maxradius, flags) : null;
  }

  @Override
  protected Logging getLogger() {
    return LOG;
  }
}
