package org.yournamehere.client;

import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.grid.ListGridRecord;
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 java.util.LinkedHashMap;

public class MyTreeGrid extends TreeGrid {
    private TreeGridField fields[] = null;
    private LinkedHashMap<String, String> aMap = new LinkedHashMap<String, String>() {
        { put("A", "AXXXXXXXXX"); put("B", "XBXXXXXXXX"); put("C", "XXCXXXXXXX"); }
    };

    public MyTreeGrid() {
        setShowRecordComponents(true);
        setShowRecordComponentsByCell(true);

        fields = new TreeGridField[2];
        for (int col = 0; col < fields.length; col++)
            fields[col] = new TreeGridField("column" + col, "Column " + col);
        setFields(fields);

        Tree theTree = new Tree();
        theTree.setRoot(new TreeNode("root", addNodes()));
        setData(theTree);

        theTree.openAll();
    }
    @Override
    public Canvas updateRecordComponent(ListGridRecord record, Integer col, Canvas component, boolean recordChanged) {
        System.err.println("updateRecordComponent(" + record + ", "  +col + ", " + component + ", " + recordChanged + ")");
        return component;
    }

    @Override
    protected Canvas createRecordComponent(ListGridRecord record, Integer col) {
        System.err.println("createRecordComponent(" + record + ", " + col + ")");
        if (col == 1) return selectionList((Cell)record.getAttributeAsObject("data1"));
        else return null;
    }

    private TreeNode addNodes() {
        TreeNode node11 = new TreeNode();
        node11.setAttribute(fields[0].getName(), "0.1");
        node11.setAttribute("data1", new Cell(aMap, "Selection11"));

        TreeNode node12 = new TreeNode();
        node12.setAttribute(fields[0].getName(), "0.2");
        node12.setAttribute("data1", new Cell(aMap, "Selection12"));

        TreeNode node1 = new TreeNode("node1", node11, node12);
        for (int col = 0; col < fields.length; col++) {
            Cell cell = new Cell(col + ".0");
            node1.setAttribute(fields[col].getName(), cell.data());
            node1.setAttribute("data" + col, cell);
        }
        return node1;
    }
    private Canvas selectionList(Cell cell) {
        if (!cell.hasValueMap()) return null;

        SelectItem selection = new SelectItem("selection", "");
        selection.setValueMap(cell.valueMap());

        DynamicForm form = new DynamicForm();
        form.setID(cell.data());
        form.setBackgroundColor("yellow");
        form.setFields(selection);
        form.setHeight100();
        return form;
    }
}
