/* ColTracker.java

	Purpose:
		
	Description:
		
	History:
		Oct 24, 2014 2:17:46 PM, Created by henrichen

	Copyright (C) 2014 Potix Corporation. All Rights Reserved.
*/

package org.zkoss.zssex.model.sys;

import java.io.Serializable;
import java.util.Collection;

import org.zkoss.zss.model.sys.dependency.Ref;
import org.zkoss.zssex.util.Interval;
import org.zkoss.zssex.util.Interval.InfiniteInterval;
import org.zkoss.zssex.util.IntervalTree;

/**
 * Tracking column references.
 * @author henri
 *
 */
class ColTracker implements Serializable {
	private static final long serialVersionUID = 759454443856972536L;
	private int _maxColLimit;
	private IntervalTree<Ref> _colIntervalTree;
	
	ColTracker(int maxColLimit) {
		_maxColLimit = maxColLimit;
		_colIntervalTree = new IntervalTree<Ref>(maxColLimit);
	}

	Interval<Ref> insertRef(Ref ref) {
		Interval<Ref> interval = prepareKeyInterval(ref, ref);
		return _colIntervalTree.insertInterval(interval, null);
	}
	
	Interval<Ref> deleteRef(Ref ref) {
		Interval<Ref> interval = prepareKeyInterval(ref, ref);
		return _colIntervalTree.deleteInterval(interval, null);
	}
	
	Interval<Ref> searchRef(Ref ref) {
		Interval<Ref> interval = prepareKeyInterval(ref, null);
		return _colIntervalTree.searchInterval(interval);
	}
	
	Collection<Interval<Ref>> overlaps(Ref ref) {
		Interval<Ref> interval = prepareKeyInterval(ref, null);
		return _colIntervalTree.overlaps(interval);
	}
	
	boolean isEmpty() {
		return _colIntervalTree.isEmpty();
	}
	
	private Interval<Ref> prepareKeyInterval(Ref ref, Ref payload) {
		final int col1 = ref.getColumn();
		final int col2 = ref.getLastColumn();
		return col1 <= 0 && col2 < 0 ? 
				new InfiniteInterval<Ref>(_maxColLimit, payload) :
				new Interval<Ref>(col1, col2, payload);
	}
}
