package com.one;

import java.util.Random;

public class SlidingNumber
{
	protected static final int FP_SHIFT = 16;
	protected static Random rnd = new Random();
	
	protected int current, target, delta;
	protected int minvalue, maxvalue;
	protected int mindelta, maxdelta;
	
	public SlidingNumber(int minvalue, int maxvalue, int minsteps, int maxsteps)
	{
		this.minvalue = minvalue;
		this.maxvalue = maxvalue;
		
		mindelta = ((maxvalue - minvalue) << FP_SHIFT) / maxsteps;
		maxdelta = ((maxvalue - minvalue) << FP_SHIFT) / minsteps;
		
		current = (minvalue + (rnd.nextInt() & 0x7FFFFFFF) % (maxvalue - minvalue + 1)) << FP_SHIFT;
		updateCourse();
	}
	
	public SlidingNumber(int minvalue, int maxvalue, int value, int minsteps, int maxsteps)
	{
		this.minvalue = minvalue;
		this.maxvalue = maxvalue;
		
		mindelta = ((maxvalue - minvalue) << FP_SHIFT) / maxsteps;
		maxdelta = ((maxvalue - minvalue) << FP_SHIFT) / minsteps;
		
		setValue(value);
	}

	public void setValue(int value)
	{
		if(value < minvalue)
		{
			value = minvalue;
		}
		else if(value > maxvalue)
		{
			value = maxvalue;
		}

		current = value << FP_SHIFT;
		updateCourse();
	}
	
	public int nextValue()
	{
		current += delta;
		
		if(delta > 0)
		{
			if(current >= target)
			{
				updateCourse();
			}
		}
		else if(delta < 0)
		{
			if(current <= target)
			{
				updateCourse();
			}
		}
		
		return current >>> FP_SHIFT;
	}
	
	protected void updateCourse()
	{
		target = (minvalue + (rnd.nextInt() & 0x7FFFFFFF) % (maxvalue - minvalue + 1)) << FP_SHIFT;
		delta = (target < current ? -1 : 1) * (mindelta + (rnd.nextInt() & 0x7FFFFFFF) % (maxdelta - mindelta + 1));
	}
}
