const fields = [
  { fieldName: "Category", dataType: "text" },
  { fieldName: "Menu", dataType: "text" },
  { fieldName: "MenuLabelField", dataType: "text" }
];

function getCategoryIndex(category) {
  const categories = ["Korean Food", "Chinese Food", "Japanese Food", "Form", "Dessert", "Fast Food"];
  return categories.indexOf(category) + 1;
}

async function getLists(categoryIndex, grid) {
  return new Promise((resolve, reject) => {
    grid.showLoading(true);
    const url = `list${categoryIndex}.json`;
    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then(data => {
        setTimeout(() => {
          grid.closeLoading();
          resolve({
            value: "value",
            label: "label",
            list: data
          });
        }, 500);
      })
      .catch(error => {
        console.log(error);
        grid.closeLoading();
        reject(error);
      });
  });
}

const columns = [
  {
    name: "Category",
    fieldName: "Category",
    width: "150",
    header: { text: "Category" }
  },
  {
    name: "Menu",
    fieldName: "Menu",
    width: "150",
    lookupDisplay: true,
    labelField: "MenuLabelField",
    editButtonVisibility: "always",
    editor: {
      type: "list",
      listCallback: async (grid, index) => {
        const category = grid.getValue(index.itemIndex, 'Category');
        const categoryIndex = getCategoryIndex(category);
        return await getLists(categoryIndex, grid);
      }
    },
    header: { text: "Menu" }
  },
  {
    name: "MenuLabelField",
    fieldName: "MenuLabelField",
    header: { text: "Label Field" }
  }
];

const { gridView, dataProvider } = RealGrid.createGrid("realgrid", {
  columns,
  header: { height: 40 },
  display: { rowHeight: 36, emptyMessage: "No data to display." },
  footer: { height: 40 },
  stateBar: { width: 16 },
  edit: { insertable: true, appendable: true },
  onGetEditValue: (grid, index, result) => {
    if (index.column === "Menu") {
      const value = result["item"] ? result["item"].label : result["text"];
      grid.setValue(index.itemIndex, "MenuLabelField", value);
    }
  },
  onInitialized: (grid) => {
    fetch('/data/en/listcallback_data.json')
      .then(response => response.json())
      .then(data => {
        grid.getDataSource().setRows(data);
      });
  }
}, {
  fields
});

window.gridView = gridView;
window.dataProvider = dataProvider;