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

import java.awt.image.ImageObserver;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;

class      AnimatedSprite 
extends    Sprite
implements Runnable
{
	public  AnimationRule animation_rule;
	private Thread        animation_thread;
	
	private boolean animate = false;


    /**
     *  This constructor creates an Raster initialized
     *  with the contents of an image.
     */
    public AnimatedSprite( Image img, AnimationRule animation_rule )
    {
		super( img );
		this.animation_rule = animation_rule;
    }


    /**
     *  Draw the sprite on the input raster. Return the Rectangle
	 *  that we modified.
     */
    public Rectangle
	draw( Raster raster )
    {
		Rectangle clip = animation_rule.getCurrentClips();
		
		int last_row    = clip.y + clip.height;
		int last_column = clip.x + clip.width;
		
		for ( int i=clip.y; i<last_row; i++ ) {
			for( int j=clip.x; j<last_column; j++ ) {
				if ( !isTransparent( pixel[i*width+j] ) ) {
					raster.setPixel( pixel[i*width+j], x+j-clip.x, y+i-clip.y );
				}
			}
		}
		
		System.out.println( "Drawing the AnimatedSprite" );
		
		return new Rectangle( x, y, clip.width, clip.height );
    }


    /**
     *  Point to the next clip
     */
    public void
	next()
    {
		System.out.println( "Changing to clip " + animation_rule.current_clip );
		animation_rule.next();
	}


    /**
     *  Start animation
     */
    public void
	startAnimation()
    {
		System.out.println( "Starting animation" );
		animate          = true;
		animation_thread = new Thread( this, "AnimationThread" );
		animation_thread.start();
	}


    /**
     *  Run
     */
    public void
	run()
    {
		while ( true ) {
			try {
				animation_thread.sleep( animation_rule.getCurrentDelay() );
			} catch ( Exception e ) {
				System.out.println( "AnimatedSprite exception in sleeping" );
				e.printStackTrace( System.out );
			}
			if ( animate ) {
				next();
			}
		}
	}


    /**
     *  Stop animation
     */
    public void
	stopAnimation()
    {
		animate = false;
	}
}
