 
 package com.threerings.flash {
 
-import flash.display.*;
-import flash.events.*;
+import flash.display.BitmapData;
+
+import flash.events.Event;
+import flash.events.EventDispatcher;
+import flash.events.TimerEvent;
+
 import flash.utils.Timer;
 
 import com.threerings.util.ValueEvent;

/**
 * Class that will encode a jpeg in the background and fire an event when it's done.
 */
public class BackgroundJPGEncoder extends EventDispatcher {
    
    /**
     * Construct a jpeg encoder.  Once started, the encoder will encode a jpeg over the course
     * of multiple frames, generating an event to deliver the finished jpeg when it is done.

     * @param quality The jpeg quality from 1 to 100 which determines the compression level.
     * @param timeSlice The number of milliseconds of processing to do per frame.  
     */
    public function BackgroundJPGEncoder (
        image :BitmapData, quality :Number = 50, timeSlice :int = 100)
    {
        _timeSlice = timeSlice;
        _encoder = new JPGEncoder(image, quality, PIXEL_GRANULARITY);
        _timer = new Timer(1);
        _timer.addEventListener(TimerEvent.TIMER, timerHandler);
    }
    
    /**
     * Start encoding
     */
    public function start () :void 
    {
        _timer.start();
    }
    
    /**
     * Cancel encoding and discard any intermediate results.
     */	
    public function cancel () :void
    {
        _timer.stop();
        _timer = null;
        _encoder = null;
    }
    
    protected function timerHandler (event :TimerEvent) :void
    {
        if (_encoder.process(_timeSlice)) {
            _timer.stop();
            // The jpeg is ready so we fire an event passing it to the consumer.
            dispatchEvent(new ValueEvent(Event.COMPLETE, _encoder.getJpeg()));
        } 
    }
    
    protected var _timeSlice :int;
    protected var _timer :Timer;
    protected var _encoder :JPGEncoder; 
    
    protected const PIXEL_GRANULARITY :int = 100;
}
}
