/** 
 * Copyright 2005-2007 Xue Yong Zhi, Jie Li, Ye Zheng
 * Distributed under the GNU General Public License 2.0
 */

package com.xruby.runtime.value;

import com.xruby.runtime.lang.*;


public class RubyRange extends RubyBasic {
	private RubyValue begin_;
	private RubyValue end_;
	private boolean exclude_end_;

	RubyRange() {
		super(RubyRuntime.RangeClass);
	}

	public void setValue(RubyValue left, RubyValue right, boolean isExclusive) {
		RubyMethod m = left.findMethod("<=>");
		if (m == null){
			throw new RubyException(RubyRuntime.ArgumentErrorClass, "bad value for range");
		}
		RubyArray args = new RubyArray();
		args.add(right);
		try {
			RubyValue result = m.invoke(left, args, null);
			if (result == ObjectFactory.nilValue){
				throw new RubyException(RubyRuntime.ArgumentErrorClass, "bad value for range");
			}
		} catch (RubyException exception){
			if (exception.getRubyValue().getRubyClass() == RubyRuntime.ArgumentErrorClass){
				throw new RubyException(RubyRuntime.ArgumentErrorClass, "bad value for range");
			}
			throw exception;
		}

		begin_ = left;
		end_ = right;
		exclude_end_ = isExclusive;
	}
	
	public RubyValue getLeft() {
		return begin_;
	}
	
	public RubyValue getRight() {
		return end_;
	}
	
	public boolean isExcludeEnd() {
		return exclude_end_;
	}

	public RubyArray to_a() {
		RubyArray a = new RubyArray();
		//TODO may not be RubyFixnum
		int left = ((RubyFixnum)begin_).intValue();
		int right = ((RubyFixnum)end_).intValue();
		if (!exclude_end_) {
			++right;
		}
		for (int i = left; i < right; ++i) {
			a.add(ObjectFactory.createFixnum(i));
		}
		return a;
	}
}

@@ -461,157 +461,9 @@
 e) %7B
-%0D%0A%09%09RubyMethod m = left.findMethod(%22%3C=%3E%22);%0D%0A%09%09if (m == null)%7B%0A%09%09%09throw new RubyException(RubyRuntime.ArgumentErrorClass, %22bad value for range%22);%0A%09%09%7D
 %0A
+
 %09%09Ru
@@ -549,16 +549,26 @@
 t = 
-m.invoke
+RubyAPI.callMethod
 (lef
@@ -580,16 +580,23 @@
 gs, null
+, %22%3C=%3E%22
 );%0A%09%09%09if

use more RubyAPI