package jp.ac.kyutech.mns.ist;

import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Hashtable;

import edu.umd.cs.piccolo.PCamera;
import edu.umd.cs.piccolo.activities.PTransformActivity;
import edu.umd.cs.piccolo.event.PInputEvent;

public class SimpleATN_animateCameraView implements Runnable {
	PCamera camera;
	Rectangle2D rect;
	int msec;
	Thread thread;
	static ArrayList<PTransformActivity> animList = new ArrayList<PTransformActivity>();
	static Hashtable<PInputEvent,Long> eventsForZoom = new Hashtable<PInputEvent,Long>();

	public SimpleATN_animateCameraView(PCamera cam, Rectangle2D _rect, int m, PInputEvent aEvent){
		camera = cam;
		rect = _rect;
		msec = m;
		if (aEvent != null){
			for(PInputEvent ev: eventsForZoom.keySet()){
				if (Math.abs(ev.getWhen()-System.currentTimeMillis())<2000) eventsForZoom.remove(ev);
			}
			if (eventsForZoom.get(aEvent) != null){
				if (Math.abs(eventsForZoom.get(aEvent)-System.currentTimeMillis())<2000) return;
			}
		}
		thread = new Thread(this);
		thread.start();
	}
	@Override
	public void run() {
		while(true){
			boolean isAnimating = false;
			ArrayList<PTransformActivity> tobeRemoved = new ArrayList<PTransformActivity>();
			for(PTransformActivity t: animList){
				if (t.isStepping()) {
//					t.terminate();
//					System.out.println("Animating...");
					isAnimating = true;
				}
				if (t.getStopTime()< System.currentTimeMillis()){
					tobeRemoved.add(t);
				}
			}
			for(PTransformActivity t: tobeRemoved) animList.remove(t);
			if (isAnimating){
				try {
//					System.out.println("Stop Animating...");
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				break;
			}
		}
		PTransformActivity ta = camera.animateViewToCenterBounds(rect, true, msec);
		animList.add(ta);	
	}
}
