package openperipheral.api.helpers;

import com.google.common.primitives.Ints;

/**
 * Simple class for easy handling of not-zero indexed collections.
 * If used, OpenPeripheral will convert any index to zero-base value with script language specific offset.
 * For example, in Lua value 3 will become {@code Index(value = 2, offset = 1}.
 */
public class Index extends Number implements Comparable<Index> {
	private static final long serialVersionUID = 1L;

	public int offset;

	public final int value;

	public Index(int value, int offset) {
		this.value = value - offset;
		this.offset = offset;
	}

	public Index(int value) {
		this.value = value;
	}

	public Integer box() {
		return Integer.valueOf(value);
	}

	public int unbox() {
		return value;
	}

	@Override
	public int intValue() {
		return value + offset;
	}

	@Override
	public long longValue() {
		return intValue();
	}

	@Override
	public float floatValue() {
		return intValue();
	}

	@Override
	public double doubleValue() {
		return intValue();
	}

	@Override
	public boolean equals(Object obj) {
		return (obj instanceof Index) && (value == ((Index)obj).value);
	}

	@Override
	public int compareTo(Index other) {
		return Integer.compare(this.value, other.value);
	}

	@Override
	public int hashCode() {
		return Ints.hashCode(value);
	}

	@Override
	public String toString() {
		return Integer.toString(value + offset);
	}

	public void checkElementIndex(int size, int index) {
		if (size < 0) throw new IllegalArgumentException("Negative size: " + size);

		if (index < 0) throw new IndexOutOfBoundsException(String.format("Index %d must be larger than %d", index + offset, offset));
		if (index >= size) throw new IndexOutOfBoundsException(String.format("Index %d less than %d", index + offset, size + offset));
	}

}

@@ -1385,24 +1385,25 @@
 offset);%0A%09%7D%0A
+%09
 %0A%09public voi
@@ -1426,27 +1426,29 @@
 dex(
-int siz
+String nam
 e, int 
-index
+size
 ) %7B%0A
@@ -1532,21 +1532,21 @@
 %0A%0A%09%09if (
-index
+value
  %3C 0) th
@@ -1594,24 +1594,23 @@
 format(%22
-Index 
+%25s (
 %25d
+)
  must be
@@ -1614,30 +1614,33 @@
  be 
-larger than %25d%22, index
+at least %25d%22, name, value
  + o
@@ -1662,21 +1662,21 @@
 ;%0A%09%09if (
-index
+value
  %3E= size
@@ -1732,16 +1732,23 @@
 at(%22
-Index %25d
+%25s (%25d) must be
  les
@@ -1759,21 +1759,27 @@
 an %25d%22, 
-index
+name, value
  + offse
@@ -1802,10 +1802,93 @@
 ));%0A%09%7D%0A%0A
+%09public void checkElementIndex(int size) %7B%0A%09%09checkElementIndex(%22index%22, size);%0A%09%7D%0A%0A
 %7D%0A

Fix Index checker method