/*******************************************************************************
 * Copyright (c) 2000, 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.swt.widgets;

import org.eclipse.swt.graphics.Image;

import intrinsic.Class;
import intrinsic.Function;
import intrinsic.flash.display.DisplayObject;
import intrinsic.flash.events.IEventDispatcher;
import intrinsic.mx.core.BitmapAsset;
import intrinsic.mx.core.UIComponent;

class SWTBitmapAsset extends BitmapAsset {
	Widget widget;

public SWTBitmapAsset() {
	addEventListener(intrinsic.flash.events.Event.ADDED, handleAddedFunction(), false, 0, true);
}

static native Class getClazz()/*{
	return SWTBitmapAsset;
}*/;

void handleAdded (intrinsic.flash.events.Event event) {
	DisplayObject temp = this.parent;
	if (temp == null) return;
	Display display = Display.getCurrent();
	if ("cursorHolder".equals(temp.toString())) {
		bitmapData = display.getCursorBitmap();
		return;
	}
	widget = null;
	while (temp != null) {
		if (temp instanceof UIComponent) {
			widget = display.getWidget((UIComponent)temp);
			if (widget != null) break;
		}
		temp = temp.parent;
	}
	if (widget == null) return; 
	Image image = widget._getImage(this.parent);
	if (image == null) return;
	if (image.object != null) {
		bitmapData = image.object;
	} else {
		image.listener.addEventListener(intrinsic.flash.events.Event.COMPLETE, handleCompleteFunction ());
	}
}

native Function handleAddedFunction ()/*{
	return handleAdded__Lflash_events_Event_2;
}*/;

void handleComplete (intrinsic.flash.events.Event event) {
	Image image = widget._getImage(this.parent);
	if (image.object != null) bitmapData = image.object;
	((IEventDispatcher)event.target).removeEventListener (intrinsic.flash.events.Event.COMPLETE, handleCompleteFunction ());
}

native Function handleCompleteFunction ()/*{
	return handleComplete__Lflash_events_Event_2;
}*/;
}
