import java.io.*;
import java.util.*;
import xxl.collections.*;
import xxl.cursors.*;
import xxl.functions.*;
import xxl.indexStructures.*;
import xxl.io.*;
import xxl.spatial.*;

class RTreeTest {
	/* Creates an RTree with minimum (maximum) capacity given by
	   the command line argument 0 (1) by inserting all KPEs from file rr_small.bin.
	   Performs thereafter an index nested loops join by querying all KPEs from file st_small.bin.
	*/
	public static void main (String [] args) throws Exception {
		RTree rtree = new RTree();
		int minCapacity = args.length<1? 5: Integer.parseInt(args[0]);
		int maxCapacity = args.length<2? 9: Integer.parseInt(args[1]);
		final int dimensions = 2;
		int bufferSize = 100;
		Container container = new BufferedContainer(
			new ConverterContainer(
				new BlockFileContainer("RTree", 4+2+40*maxCapacity),
				rtree.nodeConverter(
					new ConvertableConverter(
						new Function () {
							public Object invoke () {
								return new KPE(dimensions);
							}
						}
					),
					LongConverter.PROTOTYPE,
					dimensions
				)
			),
			new LRUBuffer(bufferSize),
			true
		);
		Function getDescriptor = new Function () {
			public Object invoke (Object kpe) {
				return ((KPE)kpe).rectangle;
			}
		};

		rtree.initialize(getDescriptor, container, minCapacity, maxCapacity);

		Iterator objects = new FileInputIterator(
			new Function() {
				public Object invoke(){
					return new KPE(2);
				}
			},
			new File("/home/mirzam/dittrich/newXXL/rr_small.bin")
		);

		long time = System.currentTimeMillis();
		while (objects.hasNext())
			rtree.insert(objects.next());
		System.out.println("Insertion complete, time: "+(-time+(time = System.currentTimeMillis()))+"ms");
		rtree.checkDescriptors();

		Iterator queries = new FileInputIterator(
			new Function() {
				public Object invoke(){
					return new KPE(2);
				}
			},
			new File("/home/mirzam/dittrich/newXXL/st_small.bin")
		);
		int results = 0;

		time = System.currentTimeMillis();
		while (queries.hasNext())
			results += Cursors.count(rtree.query(((KPE)queries.next()).rectangle));
		System.out.println("Query results: "+results+", time: "+(-time+(time = System.currentTimeMillis()))+"ms");
		container.close();
	}
}
