package studio.junk.jam.coloritum.ui.animation;

/**
 * @author marvin
 */
public class AnimationWorker implements Runnable, AnimationControl {

	public final Animation		element;
	public final long			threadSleep;
	public final long			timeStepCount;
	public final double			valueDiff;
	public final long			timeStep;

	protected Thread			thread;

	protected final Object		monitor	= new Object();

	protected volatile boolean	paused	= false;

	public AnimationWorker(Animation element) {
		this.element = element;
		this.threadSleep = (long) (1000d / element.fps);
		this.timeStepCount = element.duration / threadSleep;
		this.valueDiff = element.targetValue - element.startValue;
		this.timeStep = (long) (valueDiff / timeStepCount);
	}

	@Override
	public void run() {
		thread = Thread.currentThread();

		try {
			for (long i = 0; i < timeStepCount && !Thread.interrupted(); i++) {

				Thread.sleep(threadSleep);

				double farg = (double) i / timeStepCount;
				double fout = element.f(farg);

				element.callback.callback(element.startValue + fout * valueDiff);

				if (i == timeStepCount - 1 && element.endless) {
					i = 0;
				}

				synchronized (monitor) {
					if (paused) {
						monitor.wait();
					}
				}

			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void cancelAnimation() {
		if (thread == null || !thread.isAlive())
			throw new IllegalStateException("No thread");

		thread.interrupt();
	}

	@Override
	public void pauseAnimation() {
		synchronized (monitor) {
			if (paused)
				return;

			paused = true;
		}
	}

	@Override
	public void continueAnimation() {
		synchronized (monitor) {
			if (!paused)
				return;

			paused = false;
			monitor.notify();
		}

	}

}
