package com.gwt.client.widget;

import java.util.LinkedHashMap;
import java.util.Map;

import com.smartgwt.client.types.AutoFitWidthApproach;
import com.smartgwt.client.types.Autofit;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
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.layout.VLayout;
import com.smartgwt.client.widgets.layout.VStack;

/**
 * @author hari_k
 * 
 */
public class TestListingWidget extends Canvas {
  private VStack mainPanel;
  private ListGrid listGrid;

  public TestListingWidget() {
    getSmartVLayout();
  }

  private void getSmartVLayout() {
    VLayout mainLayout = new VLayout();
    setWidth100();
    setHeight100();
    mainLayout.addMember(getMainPanel());
    addChild(mainLayout);
  }

  private VStack getMainPanel() {
    if (mainPanel == null) {
      mainPanel = new VStack();
      setWidth100();
      setHeight100();
      mainPanel.addMember(getListingTable());
    }
    return mainPanel;
  }

  private ListGrid getListingTable() {
    if (listGrid == null) {
      listGrid = new ListGrid() {
        @Override
        protected String getCellCSSText(ListGridRecord record, int rowNum, int colNum) {
          String cellCSS = super.getCellCSSText(record, rowNum, colNum);
          cellCSS = (cellCSS == null) ? "" : cellCSS;
          // under line name
          if ("NAME".equals(getFieldName(colNum))) {
            cellCSS += "text-decoration:underline;";
          }
          return cellCSS;
        }

        @SuppressWarnings("rawtypes")
        @Override
        protected Canvas createRecordComponent(final ListGridRecord record, final Integer colNum) {
          int rowNum = listGrid.getRecordIndex(record);
          String fieldName = this.getFieldName(colNum);
          if (fieldName != null && fieldName.equals("Action")) {
            final ComboBoxItem cbItem = new ComboBoxItem();
            LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>();

            Map recordMap = listGrid.getRecord(rowNum).toMap();

            valueMap.put("Select", "Select");
            valueMap.put("Details_" + rowNum, "Details");
            valueMap.put("Edit_" + rowNum, "Edit");
            valueMap.put("Delete_" + rowNum, "Delete");
            cbItem.setValueMap(valueMap);
            cbItem.setShowTitle(false);
            cbItem.setDefaultToFirstOption(true);
            cbItem.setWidth(100);

            cbItem.addChangedHandler(new com.smartgwt.client.widgets.form.fields.events.ChangedHandler() {
              @Override
              public void onChanged(ChangedEvent event) {
                String value = event.getValue().toString().split("_")[0];
                int rowIndex = Integer.parseInt(event.getValue().toString().split("_")[1]);

                Map recordMap = listGrid.getRecord(rowIndex).toMap();
                // My logic
              }
            });

            DynamicForm f = new DynamicForm();
            f.setItems(cbItem);

            return f;
          } else {
            return null;
          }
        }
      };

      setWidth100();
      // setHeight("330px");

      listGrid.setDateFormatter(DateDisplayFormat.TOSERIALIZEABLEDATE);
      listGrid.setShowFilterEditor(Boolean.TRUE);
      listGrid.setAlternateRecordStyles(Boolean.FALSE);
      listGrid.setBaseStyle("boxedGridCell");
      listGrid.setCanEdit(false);
      listGrid.setAutoSaveEdits(Boolean.FALSE);
      listGrid.setShowRollOver(Boolean.FALSE);
      listGrid.setAutoFitFieldWidths(true);
      listGrid.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH);
      listGrid.setCanGroupBy(false);
      listGrid.setCanMultiSort(false);
      listGrid.setCanAutoFitFields(false);
      listGrid.setAutoFitData(Autofit.VERTICAL);
      listGrid.setAutoFitMaxRecords(10);

      // Number of records to fetch at a time.
      listGrid.setDataPageSize(25);

      // If this setModalEditing is set to true, any mouse click outside of the
      // open cell editors will end editing mode,
      // hiding the cell editors and saving any changes to those cell values.
      listGrid.setModalEditing(false);
      listGrid.setSelectionType(SelectionStyle.MULTIPLE);
      listGrid.setFastCellUpdates(false);
      listGrid.setCanDragSelectText(true);

      listGrid.setShowRecordComponents(true);
      listGrid.setShowRecordComponentsByCell(true);
      // listGrid.setInitialSort(initialSort);
      listGrid.setEmptyMessage(listGrid.getLoadingDataMessage());

      // listGrid.addDataArrivedHandler(getLoadingDataMessage());

      ListGridField id = new ListGridField("ID", "ID");
      id.setHidden(true);

      ListGridField name = new ListGridField("NAME", "NAME");
      name.setCanFilter(false);
      name.setCanSort(false);

      ListGridField action = new ListGridField("Action", "Action");
      action.setCanFilter(false);
      action.setCanSort(false);

      ListGridField shortName = new ListGridField("SHORT_NAME", "SHORT_NAME");
      shortName.setCanFilter(false);
      shortName.setCanSort(false);

      ListGridField description = new ListGridField("DESCRIPTION", "DESCRIPTION");
      description.setCanFilter(false);
      description.setCanSort(false);

      ListGridField dataType = new ListGridField("DATATYPE", "DATATYPE");
      dataType.setCanFilter(false);
      dataType.setCanSort(false);

      ListGridField flag = new ListGridField("FLAG", "FLAG");
      flag.setCanFilter(false);
      flag.setCanSort(false);
      flag.setDefaultValue("false");

      listGrid.setFields(id, name, action, shortName, description, dataType, flag);

      loadData();
    }
    return listGrid;
  }

  private void loadData() {
    ListGridRecord[] allListGridRecordAry = { new ListGridRecord() };
    for (int i = 0; i < 10; i++) {
      ListGridRecord listGridRecord = new ListGridRecord();
      listGridRecord.setAttribute("ID", i);
      listGridRecord.setAttribute("NAME", "NAME " + i);
      listGridRecord.setAttribute("SHORT_NAME", "SHORT_NAME " + i);
      listGridRecord.setAttribute("DESCRIPTION", "DESCRIPTION " + i);
      listGridRecord.setAttribute("DATATYPE", "DATATYPE " + i);
      listGridRecord.setAttribute("FLAG", "true");

      allListGridRecordAry[i] = listGridRecord;
    }
    listGrid.setData(allListGridRecordAry);
  }
}
