package cz.fidentis.analyst.registration;

import cz.fidentis.analyst.canvas.Direction;
import com.jogamp.opengl.util.FPSAnimator;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Animator used to animate transformations of model.
 * Based on {@link cz.fidentis.analyst.canvas.RotationAnimator}.
 * 
 * @author Richard Pajersky
 */
public class ModelRotationAnimator {
    
    /**
     * Frequency of the rotation or zoom animations
     */
    private static final int FPS = 60; 
    
    /**
     * Animator used when the rotation or zoom buttons are pressed and held
     */
    private final FPSAnimator animator;
    
    /*
     * Animation timer
     */
    private long startClickTime = 0;
    private TimerTask task;
    private Timer timer;
    
    private Direction direction = Direction.NONE;
    
    /**
     * Constructor.
     */
    public ModelRotationAnimator() {
        this.animator = new FPSAnimator(FPS, true);
    }
    
    /**
     * Starts model animation
     * @param dir Transform direction
     * @param panel Panel
     */
    public void startModelAnimation(Direction dir, RegistrationPanel panel) {
        if (this.direction != Direction.NONE) {
            throw new UnsupportedOperationException(); // this should no happen
        }
        
        animator.start();
        timer = new Timer();
        startClickTime = System.currentTimeMillis();
        task = new TimerTask() {
            @Override
            public void run() {
                panel.transform(dir);
            }
        };
        timer.schedule(task, 500, 100);
        
        this.direction = dir;        
    }
    
    /**
     * Stops the animation.
     */
    public void stopModelAnimation(RegistrationPanel panel) {
        timer.cancel();
        if ((System.currentTimeMillis() - startClickTime) < 500) {
                panel.transform(direction);
        }
        startClickTime = 0;
        animator.stop();
        this.direction = Direction.NONE;
    }    
}
