/*******************************************************************************
 * 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.internal.flex;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;

import intrinsic.Function;
import intrinsic.flash.display.Bitmap;
import intrinsic.flash.events.MouseEvent;
import intrinsic.mx.containers.HBox;
import intrinsic.mx.controls.CheckBox;
import intrinsic.mx.controls.Image;
import intrinsic.mx.core.ScrollPolicy;
import intrinsic.mx.core.UITextField;

public class TableItemRenderer extends HBox {
/*+
  override public function set data(value:Object):void
	{
		super.data = value;
		invalidateProperties();
	}
+*/
	Table table;
	TableColumn column;
	boolean headerRenderer;
	UITextField text;
	Image image;
	CheckBox checkBox;
	
	public TableItemRenderer(Table parent, TableColumn column, boolean headerRenderer) {
		this.table = parent;
		this.column = column;
		this.headerRenderer = headerRenderer;
		verticalScrollPolicy = ScrollPolicy.OFF; 
		horizontalScrollPolicy = ScrollPolicy.OFF;
	}
	
	void clickHandler(MouseEvent event) {
		TableItem item = (TableItem)data;
		item.setChecked(checkBox.selected);
//		table.postEvent(SWT.Selection);
	}

	native Function clickHandlerFunction ()/*{
		return clickHandler__Lflash_events_MouseEvent_2;
	}*/;
	
	protected void createChildren() {
		super.createChildren();
		if ((table.getStyle() & SWT.CHECK) != 0 && !headerRenderer) {
			int index = table.indexOf(column);
			if (index == 0) {
				checkBox = new CheckBox();
				this.setStyle("paddingLeft", 4);
				addChild(checkBox);
				checkBox.addEventListener(MouseEvent.CLICK, clickHandlerFunction ());
			}
		}
		image = new Image();
		addChild(image);
		text = new UITextField();
		addChild(text);
	}
	
	public void validateProperties() {
		super.validateProperties();
		String string;
		org.eclipse.swt.graphics.Image img;
		if (headerRenderer) {
			string = column.getText();
			img = column.getImage();
		} else {
			TableItem item = (TableItem)data;
			if (item == null) return;
			int index = column != null ? table.indexOf(column) : 0;
			if (checkBox != null) {
				checkBox.selected = item.getChecked();
			}
			string = item.getText(index);
			img = item.getImage(index); 
		}
		text.text = string;
		image.source = img != null ? new Bitmap(img.object) : null;
	}
}