const fields = [
  { fieldName: "area1code", dataType: "text" },
  { fieldName: "area1name", dataType: "text" },
  { fieldName: "area2code", dataType: "text" },
  { fieldName: "area2name", dataType: "text" },
  { fieldName: "area3code", dataType: "text" },
  { fieldName: "area3name", dataType: "text" },
  { fieldName: "treeId", dataType: "text" },
  { fieldName: "treeName", dataType: "text" },
  { fieldName: "iconField", dataType: "text" }
];

const columns = [
  { fieldName: "treeName", name: "treeName", width: 150, header: { text: "Region Name" } },
  { fieldName: "treeId", name: "treeId", header: { text: "TreeID" }, visible: false },
  { fieldName: "area1code", name: "area1code", header: { text: "Province Code" }, visible: false },
  { fieldName: "area1name", name: "area1name", header: { text: "Province Name" } },
  { fieldName: "area2code", name: "area2code", header: { text: "City/District Code" } },
  { fieldName: "area2name", name: "area2name", header: { text: "City/District Name" } },
  { fieldName: "area3code", name: "area3code", header: { text: "Town Code" } },
  { fieldName: "area3name", name: "area3name", header: { text: "Town Name" } },
  { fieldName: "iconField", name: "iconField" }
];

const { treeView, dataProvider } = RealGrid.createTree("realgrid", {
  columns,
  header: {
    height: 40
  },
  display: {
    rowHeight: 36,
    emptyMessage: "No data to display."
  },
  footer: {
    height: 40
  },
  stateBar: {
    width: 16
  },
  treeOptions: {
    iconVisible: false,
    templateOptions: {
      callback: (tree, model, width, height) => {
        if (model.item && model.item.level > 0) {
          let code = `area${model.item.level}code`;
          let name = `area${model.item.level}name`;
          code = tree.getValue(model.index?.itemIndex, code);
          name = tree.getValue(model.index?.itemIndex, name);
          return `<span style='color:red'>[${code}]</span> <span style='color:blue'>${name}</span>`;
        }
        return model.value;
      }
    }
  },
  onInitialized: (tree) => {
    fetch('/data/en/areatree.json')
      .then(response => response.json())
      .then(data => {
        tree.getDataSource().setRows(data, 'treeId', false, null, "iconField");
        tree.refresh();
      });
  }
}, {
  fields
});

window.treeView = treeView;
window.dataProvider = dataProvider;