// EmbedBitmap
//
// original code is written by Ben Cantrick (mackys)
// http://mackys.livejournal.com/923221.html

import flash.display.Loader;
import flash.display.LoaderInfo;

import flash.events.Event;
import flash.events.EventDispatcher;

class EmbedBitmap extends EventDispatcher {
  static public var COMPLETE:String = "EvLoadCompleted";
  private var __mystage( null, null ):flash.display.DisplayObjectContainer;
  private var __imgLoader( null, null ):Loader;

  public function new( ?s:String = null,
                       ?st:flash.display.DisplayObjectContainer = null ) {
    super();
    __mystage = null;
    if ( s != null && s != "" ) {
      loadImageFromResource( s, st );
    }
  }

  // load image data from resource name s
  public function loadImageFromResource( s:String,
                                         ?st:flash.display.DisplayObjectContainer = null ):Void {
    // are there any easy ways to verify resource name?
    // only haxe.Resource.listNames()? is try/catch possible?
    var bytes:haxe.io.Bytes = haxe.Resource.getBytes( s );
    var byteArr:flash.utils.ByteArray = bytes.getData();

    __imgLoader = new Loader();
    __imgLoader.loadBytes( byteArr );

    if ( st != null ) __mystage = st;

    // wait for load
    var li:LoaderInfo = __imgLoader.contentLoaderInfo;
    li.addEventListener( Event.INIT, __loadComplete );
  }

  private function __loadComplete( e:Event ):Void {
    __addToStage();
    dispatchEvent( new Event( COMPLETE ) );
  }

  private function __addToStage():Void {
    var mywidth:Float = 0.0;
    var myheight:Float = 0.0;
    var ratio:Float = 1.0;
    if ( __mystage == null ) {
      flash.Lib.current.stage.addChild( __imgLoader );
      mywidth = flash.Lib.current.stage.width;
      myheight = flash.Lib.current.stage.height;
    } else {
      __mystage.addChild( __imgLoader );
      mywidth = __mystage.width;
      myheight = __mystage.height;
    }
    var ratio:Float = Math.min( mywidth / __imgLoader.width,
                                myheight / __imgLoader.height );
    __imgLoader.scaleX *= ratio;
    __imgLoader.scaleY *= ratio;
    __imgLoader.x = ( mywidth - __imgLoader.width ) / 2;
    __imgLoader.y = ( myheight - __imgLoader.height ) / 2;
  }

  public function removeFromStage():Void {
    // no extra checks before removing child
    if ( __mystage == null ) {
      flash.Lib.current.stage.removeChild( __imgLoader );
    } else {
      __mystage.removeChild( __imgLoader );
    }
  }
}
