package org.test.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.ViewStateChangedEvent;
import com.smartgwt.client.widgets.grid.events.ViewStateChangedHandler;

/**
 * Main entry point.
 *
 * @author kirilv
 */
public class MainEntryPoint implements EntryPoint {

    private ListGrid grid;

    @Override
    public void onModuleLoad() {

        grid = new ListGrid() {
            @Override
            protected Canvas getExpansionComponent(final ListGridRecord record) {
                HLayout layout = new HLayout();
                layout.setWidth(getTotalGridScrolledWidth() - 25); // 25px is the framework expansion padding.
                layout.setBackgroundColor("orange");
                layout.setHeight(150);
                return layout;
            }
        };
        grid.setWidth100();
        grid.setHeight100();
        grid.setCanExpandRecords(true);
        grid.addViewStateChangedHandler(new ViewStateChangedHandler() {

            @Override
            public void onViewStateChanged(ViewStateChangedEvent event) {
                // Workaround to invalidate the nested widget
                ListGridRecord[] records = grid.getRecords();
                for (ListGridRecord rec : records) {
                    if (grid.isExpanded(rec)) {
                        // we have to reopen each expansion in order to redraw it along with its criteria
                        grid.collapseRecord(rec);
                        grid.expandRecord(rec);
                    }
                }
            }
        });

        grid.setFields(new ListGridField("id"), new ListGridField("name"));

        ListGridRecord r1 = new ListGridRecord();
        r1.setAttribute("id", "1");
        r1.setAttribute("name", "name 1");

        ListGridRecord r2 = new ListGridRecord();
        r2.setAttribute("id", "2");
        r2.setAttribute("name", "name 2");

        grid.setData(new ListGridRecord[]{r1, r2});

        RootPanel.get().add(grid);
    }

    private int getTotalGridScrolledWidth() {
        int result = 0;
        for (ListGridField f : grid.getFields()) {
            Integer width = grid.getFieldWidth(f.getName());
            result += width == null ? 0 : width;
        }
        return result;
    }
}
