/*
 *  Copyright 2002-2009 Mikhail Kryshen <mikhail@kryshen.net>
 *
 *  This file is part of BMTron.
 *
 *  BMTron is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  BMTron is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with BMTron.  If not, see <http://www.gnu.org/licenses/>.
 */

package kryshen.bmtron;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;

/**
 * Plays animations with all frames stored in a single image.
 */
public class Animator implements Runnable {
    private Image src;
    private int fw;
    private int fh;
    private int lastFrame;
    private int frame = 0;
    private long interval;
    
    private Thread animation = null;
    private Component dest = null;
    
    private int x = 0;
    private int y = 0;
    
    Animator(Image src, int fw, int fh, long interval) {
        this.src = src;
        this.interval = interval;
        this.fw = fw;
        this.fh = fh;
        this.lastFrame = src.getWidth(null) / fw - 1;
    }
    
    public void run() {
        while (frame < lastFrame && Thread.currentThread() == animation) {
            
            try {
                Thread.currentThread().sleep(interval);
            } catch (Exception e) { System.err.println(e); }
            
            synchronized (this) {
                frame++;
            }
            
            dest.repaint(x, y, fw, fh);
        }
    }
    
    private void start() {
        if (animation != null)
            return;
        
        animation = new Thread(this);
        animation.start();
    }
    
    //void stop() {
    //    animation = null;
    //}
    
    synchronized void drawFrame(Graphics g, int x, int y, Component dest) {
        this.x = x; this.y = y;
        this.dest = dest;
        
        Rectangle cb = g.getClipBounds();
        Rectangle ncb = new Rectangle(x, y, fw, fh);
        
        if (cb != null)
            ncb = ncb.intersection(cb);
        
        g.setClip(ncb.x, ncb.y, ncb.width, ncb.height);
        g.drawImage(src, x - (frame * fw), y, null);
        g.setClip(cb);
        
        start();
    }
    
    int getFrame() {
        return frame;
    }
    
    Thread getThread() {
        return animation;
    }
}
