import java.util.Date;

import com.google.gwt.i18n.client.NumberFormat;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.RecordComponentPoolingMode;
import com.smartgwt.client.types.TreeModelType;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.events.DropEvent;
import com.smartgwt.client.widgets.events.DropHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;
import com.smartgwt.client.widgets.tree.events.FolderClosedEvent;
import com.smartgwt.client.widgets.tree.events.FolderClosedHandler;
import com.smartgwt.client.widgets.tree.events.FolderOpenedEvent;
import com.smartgwt.client.widgets.tree.events.FolderOpenedHandler;

public class SimpleTestGrid extends TreeGrid {
	private static int buttonId = 1;
	private static String iconPath = "16/icons/";

	public static final TreeNode[] employeeData = new TreeNode[] {
			new EN("400", "100", "Cha Mad", "MgrChief", 20000, true),
			new EN("189", "400", "Gen Por", "Mgr Tech", 19000, true),
			new EN("265", "189", "Oli Dou", "Asset Sp", 18000, false),
			new EN("264", "189", "Che Pea", "Dsl Sys ", 17000, false),
			new EN("263", "189", "Pri Sam", "Line Wrk", 16000, false),
			new EN("188", "400", "Rog Leg", "Mgr Syst", 15000, true),
			new EN("262", "188", "Jac Des", "Line Wrk", 14000, false),
			new EN("261", "188", "Kay Mon", "Stn Opr ", 13000, false),
			new EN("260", "188", "Fra Dug", "Fire Sec", 12000, false),
			new EN("259", "188", "Jac Leb", "Purch Cl", 11000, false),
			new EN("258", "188", "Ren Xia", "Mobile E", 10000, false),
			new EN("257", "188", "Oli Heb", "Met Read", 10900, false),
			new EN("182", "400", "Tam Kan", "Mgr Site", 10800, true),
			new EN("195", "182", "Kai Kon", "Stores W", 10700, false),
			new EN("194", "182", "Fel Pip", "Dsl Sys ", 10600, false),
			new EN("193", "182", "Dar Fee", "Inventor", 10500, false) };

	public SimpleTestGrid() {
		Tree employeeTree = new Tree();
		employeeTree.setModelType(TreeModelType.PARENT);
		employeeTree.setRootValue(1);
		employeeTree.setNameProperty("Name");
		employeeTree.setIdField("EmployeeId");
		employeeTree.setParentIdField("ReportsTo");
		employeeTree.setOpenProperty("isOpen");
		employeeTree.setData(employeeData);

		TreeGridField formattedField = new TreeGridField("Name");
		formattedField.setCellFormatter(new CellFormatter() {
			@Override
			public String format(Object value, ListGridRecord record,
					int rowNum, int colNum) {
				return record.getAttributeAsString("Job") + ": " + value + " ("
						+ (rowNum + colNum) + ")";
			}
		});

		setCanEdit(true);
		setLoadDataOnDemand(false);
		setWidth("500");
		setNodeIcon(iconPath + "node.png");
		setFolderIcon(iconPath + "folder.png");
		setShowOpenIcons(false);
		setShowDropIcons(false);
		setCanReorderRecords(true);
		setCanAcceptDroppedRecords(true);
		setShowOpenIcons(false);
		setDropIconSuffix("into");
		setClosedIconSuffix("");
		setData(employeeTree);
		setAutoFetchData(true);
		setShowRecordComponents(true);
		setShowRecordComponentsByCell(true);
		RecordComponentPoolingMode pool = RecordComponentPoolingMode.RECYCLE; //.VIEWPORT; //.DATA; //.RECYCLE; -> updateRecordComponent(); 
		setRecordComponentPoolingMode(pool);

		TreeGridField salaryField = new TreeGridField("Salary");
		salaryField.setCellFormatter(new CellFormatter() {
			@SuppressWarnings("unused")
			@Override
			public String format(Object value, ListGridRecord record,
					int rowNum, int colNum) {
				if (value != null) {
					NumberFormat nf = NumberFormat.getFormat("#,##0");
					try {
						return "$" + nf.format(((Number) value).longValue());
					} catch (Exception e) {
						return value.toString();
					}
				}
				return null;
			}
		});

		TreeGridField work = new TreeGridField("Work");
		work.setWidth(70);
		work.setCanFilter(false);
		work.setCanSort(false);

		setFields(formattedField, salaryField, work);

		addFolderOpenedHandler(new FolderOpenedHandler() {
			@Override
			public void onFolderOpened(FolderOpenedEvent event) {
			}
		});
		addFolderClosedHandler(new FolderClosedHandler() {
			@Override
			public void onFolderClosed(FolderClosedEvent event) {
				invalidateRecordComponents();
			}
		});
		addDropHandler(new DropHandler() {
			@Override
			public void onDrop(DropEvent event) {
				invalidateRecordComponents();
			}
		});
	}

	public static class EN extends com.smartgwt.client.widgets.tree.TreeNode {
		public EN(String employeeId, String reportsTo, String name, String job,
				int salary, boolean isOpen) {
			setAttribute("EmployeeId", employeeId);
			setAttribute("ReportsTo", reportsTo);
			setAttribute("Name", name);
			setAttribute("Job", job);
			setAttribute("Salary", salary);
			setAttribute("isOpen", isOpen);
		}
	}

	@Override
	public Canvas updateRecordComponent(ListGridRecord record, Integer colNum,
			Canvas component, boolean recordChanged) {
		if (colNum != getFieldNum("Work")) {
			return null;
		}

		if (component != null) {
			if ("Mgr"
					.equals(record.getAttributeAsString("Job").substring(0, 3))) {
				((HLayout) component).getMember(1).hide();
				System.out.println(new Date() + " UPDATED MANAGER buttons: "
						+ record.getAttributeAsString("Name") + " (2 buttons)");
			} else {
				((HLayout) component).getMember(1).show();
				System.out.println(new Date() + " UPDATED NORMAL buttons: "
						+ record.getAttributeAsString("Name") + " (3 buttons)");
			}
			return component;
		}
		return createRecordComponent(record, colNum);
	}

	@Override
	protected Canvas createRecordComponent(final ListGridRecord record,
			Integer colNum) {
		if (colNum != getFieldNum("Work")) {
			return null;
		}

		HLayout canvas = new HLayout(3);
		canvas.setSnapTo("CC");
		canvas.setWidth(118);
		canvas.setHeight(22);

		if ("Mgr".equals(record.getAttributeAsString("Job").substring(0, 3))) {
			createNode(canvas, true);
			System.out.println(new Date() + " CREATED MANAGER buttons: "
					+ record.getAttributeAsString("Name") + " (2 buttons)");
		} else {
			createNode(canvas, false);
			System.out.println(new Date() + " CREATED NORMAL buttons: "
					+ record.getAttributeAsString("Name") + " (3 buttons)");
		}

		return canvas;
	}

	private void createNode(HLayout canvas, boolean isManager) {
		ImgButton run = getButton("delete");
		ImgButton edit = getButton("edit");
		ImgButton delete = getButton("run");

		canvas.addMember(edit);
		canvas.addMember(delete);
		canvas.addMember(run);
		if (isManager)
			canvas.getMember(1).hide();
	}

	public static ImgButton getButton(String name) {
		ImgButton button = new ImgButton();
		button.setID("_img_" + buttonId++);
		button.setShowDown(false);
		button.setShowRollOver(false);
		button.setLayoutAlign(Alignment.CENTER);
		button.setSrc(iconPath + name + ".png");
		button.setPrompt(name);
		button.setHeight(16);
		button.setWidth(16);
		return button;
	}
}
