var fields = [
  {
    fieldName: 'OrderID',
    dataType: 'text'
  },
  {
    fieldName: 'CustomerID',
    dataType: 'text'
  },
  {
    fieldName: 'EmployeeID',
    dataType: 'text'
  },
  {
    fieldName: 'OrderDate',
    dataType: 'datetime',
    datetimeFormat: 'yyyy-MM-dd'
  },
  {
    fieldName: 'CompanyName',
    dataType: 'text'
  },
  {
    fieldName: 'Country',
    dataType: 'text'
  },
  {
    fieldName: 'CountryKor',
    dataType: 'text'
  },
  {
    fieldName: 'Phone',
    dataType: 'text'
  },
  {
    fieldName: 'ProductName',
    dataType: 'text'
  },
  {
    fieldName: 'QuantityPerUnit',
    dataType: 'text'
  },
  {
    fieldName: 'Quantity',
    dataType: 'number'
  },
  {
    fieldName: 'UnitPrice',
    dataType: 'number'
  }
];

var columns = [
  {
    name: 'OrderID',
    fieldName: 'OrderID',
    editor: {
      maxLength: 5
    },
    width: '90',
    textInputCase: 'upper',
    header: {
      text: 'Text editor'
    }
  },
  {
    name: 'CompanyName',
    fieldName: 'CompanyName',
    width: '200',
    editor: {
      type: 'multiline',
      textCase: 'upper'
    },
    header: {
      text: 'Multiline Edit'
    }
  },
  {
    name: 'Quantity',
    fieldName: 'Quantity',
    width: '100',
    sortable: false,
    editor: {
      type: 'number',
      textAlignment: 'far',
      editFormat: '#,##0.##',
      multipleChar: '+'
    },
    header: {
      text: 'Number Edit'
    }
  },
  {
    name: 'CustomerID',
    fieldName: 'CustomerID',
    width: '150',
    sortable: false,
    lookupDisplay: true,
    values: ['VINET', 'HANAR', 'SUPRD', 'VICTE', 'THREE', 'SEVEN'],
    labels: ['<VINET>', '<HANAR>', '<SUPRD>', '<VICTE>', '<THREE>', '<SEVEN>'],
    editor: {
      type: 'dropdown',
      dropDownCount: 4
    },
    header: {
      text: 'DropDown Edit'
    }
  },
  {
    name: 'CustomerID2',
    fieldName: 'CustomerID',
    width: '150',
    sortable: false,
    editor: {
      type: 'dropdown',
      dropDownCount: 4,
      domainOnly: true,
      textReadOnly: true,
      values: ['VINET', 'HANAR', 'SUPRD', 'VICTE', 'THREE', 'SEVEN'],
      labels: ['<VINET>', '<HANAR>', '<SUPRD>', '<VICTE>', '<THREE>', '<SEVEN>']
    },
    header: {
      text: 'Domain Only'
    }
  },
  {
    name: 'CustomerID3',
    fieldName: 'CustomerID',
    width: '150',
    sortable: false,
    editor: {
      type: 'search',
      searchLength: 1,
      searchDelay: 1000,
      useCtrlEnterKey: true,
      useEnterKey: true
    },
    header: {
      text: 'Search Editor '
    }
  },
  {
    name: 'CountryKor',
    fieldName: 'Country',
    width: '150',
    sortable: false,
    lookupDisplay: true,
    values: ['Austria', 'Belgium', 'Brazil', 'Finland', 'France', 'Germany', 'Ireland', 'Italy', 'Mexico', 'Spain', 'Sweden', 'Switzerland', 'UK', 'USA', 'Venezuela'],
    labels: ['Austria', 'Belgium', 'Brazil', 'Finland', 'France', 'Germany', 'Ireland', 'Italy', 'Mexico', 'Spain', 'Sweden', 'Switzerland', 'UK', 'USA', 'Venezuela'],
    editor: {
      type: 'dropDown',
      dropDownCount: 5,
      partialMatch: true
    },
    header: {
      text: 'partialMatch'
    }
  },
  {
    name: 'OrderDate',
    fieldName: 'OrderDate',
    width: '180',
    sortable: false,
    editor: {
      type: 'date',
      datetimeFormat: 'yyyy.MM.dd'
    },
    header: {
      text: 'Date Edit'
    }
  },
  {
    name: 'Country',
    fieldName: 'Country',
    width: '100',
    header: {
      text: 'Country'
    }
  },
  {
    name: 'Phone',
    fieldName: 'Phone',
    width: '100',
    header: {
      text: 'Phone'
    }
  },
  {
    name: 'ProductName',
    fieldName: 'ProductName',
    width: '200',
    header: {
      text: 'Product Name'
    }
  }
];

var events = 0;
var CustomerNames = ['ALFKI', 'ANATR', 'ANTON', 'AROUT', 'BERGS', 'BLAUS', 'BLONP', 'BOLID', 'BONAP', 'BOTTM', 'BSBEV', 'CACTU', 'CENTC', 'CHOPS', 'COMMI', 'CONSH', 'DRACD', 'DUMON', 'EASTC', 'ERNSH', 'FAMIA', 'FISSA', 'FOLIG', 'FOLKO', 'FRANK', 'FRANR', 'FRANS', 'FURIB', 'GALED', 'GODOS', 'GOURL', 'GREAL', 'GROSR', 'HANAR', 'HILAA', 'HUNGC', 'HUNGO', 'ISLAT', 'KOENE', 'LACOR', 'LAMAI', 'LAUGB', 'LAZYK', 'LEHMS', 'LETSS', 'LILAS', 'LINOD', 'LONEP', 'MAGAA', 'MAISD', 'MEREP', 'MORGK', 'NORTS', 'OCEAN', 'OLDWO', 'OTTIK', 'PARIS', 'PERIC', 'PICCO', 'PRINI', 'QUEDE', 'QUEEN', 'QUICK', 'RANCH', 'RATTC', 'REGGC', 'RICAR', 'RICSU', 'ROMEY', 'SANTG', 'SAVEA', 'SEVES', 'SIMOB', 'SPECD', 'SPLIR', 'SUPRD', 'THEBI', 'THECR', 'TOMSP', 'TORTU', 'TRADH', 'TRAIH', 'VAFFE', 'VICTE', 'VINET', 'WANDK', 'WARTH', 'WELLI', 'WHITC', 'WILMK', 'WOLZA'];

function addLog(log) {
  var textarea = document.getElementById('eventLog');
  if (textarea) {
    textarea.value = textarea.value + '[' + events++ + '] ' + log + '\n';
    textarea.scrollTop = textarea.scrollHeight;
  }
}

function btnClearTextarea() {
  events = 0;
  var textarea = document.getElementById('eventLog');
  if (textarea) {
    textarea.value = '';
  }
}

function insertEmptyRow() {
  var row = gridView.getCurrent().dataRow;
  dataProvider.insertRow(Math.max(0, row), {});
}

function addEmptyRow() {
  dataProvider.addRow({});
}

function beginInsertRow() {
  if (!gridView.editOptions.insertable) {
    alert('insertable property is false.');
    return;
  }
  var curr = gridView.getCurrent();
  gridView.beginInsertRow(Math.max(0, curr.itemIndex));
}

function beginAppendRow() {
  if (!gridView.editOptions.appendable) {
    alert('appendable property is false.');
    return;
  }
  gridView.beginAppendRow();
}

function btnBeginUpdateRow() {
  var curr = gridView.getCurrent();
  gridView.beginUpdateRow(curr.itemIndex);
  gridView.showEditor();
  gridView.setFocus();
}

function btnUpdateRow() {
  gridView.commit(true);
  var curr = gridView.getCurrent();
  dataProvider.updateRow(curr.dataRow, {
    OrderID: 'Edit Name',
    CompanyName: 'Edit',
    Quantity: 0,
    Phone: 'Edit Phone',
    CustomerID: 'EditID',
    Country: 'Edit Country'
  });
}

function btnUpdateRows() {
  gridView.commit(true);
  var curr = gridView.getCurrent();
  var datas = [
    { OrderID: 'EditName1', CompanyName: 'Edit1', Quantity: 1, Phone: 'EditPhone1', CustomerID: 'EditID1', Country: 'EditCountry1' },
    { OrderID: 'EditName2', CompanyName: 'Edit2', Quantity: 2, Phone: 'EditPhone2', CustomerID: 'EditID2', Country: 'EditCountry2' },
    { OrderID: 'EditName3', CompanyName: 'Edit3', Quantity: 3, Phone: 'EditPhone3', CustomerID: 'EditID3', Country: 'EditCountry3' },
    { OrderID: 'EditName4', CompanyName: 'Edit4', Quantity: 4, Phone: 'EditPhone4', CustomerID: 'EditID4', Country: 'EditCountry4' }
  ];
  dataProvider.updateRows(curr.dataRow, datas, 0);
}

function btnUpdateRowsByDataRow() {
  gridView.commit(true);
  var datas = {
    5: { OrderID: 'EditName6', CompanyName: 'Edit6', Quantity: 0, Phone: 'EditPhone6', CustomerID: 'EditID6', Country: 'EditCountry6' },
    7: { OrderID: 'EditName8', CompanyName: 'Edit8', Quantity: 0, Phone: 'EditPhone8', CustomerID: 'EditID8', Country: 'EditCountry8' }
  };
  dataProvider.updateRowsByDataRow(datas);
}

function deleteSelection() {
  if (!gridView.editOptions.deletable) {
    alert('deletable property is false.');
    return;
  }
  gridView.deleteSelection(true);
}

function removeRow() {
  var curr = gridView.getCurrent();
  dataProvider.removeRow(curr.dataRow);
}

function DPsetValue() {
  var current = gridView.getCurrent();
  var dataRow = current.dataRow;
  var fieldName = current.fieldName;
  var value = 'Cell (' + fieldName + ', ' + dataRow + ')';
  dataProvider.setValue(dataRow, fieldName, value);
}

function GVsetValue() {
  var current = gridView.getCurrent();
  var itemIndex = current.itemIndex;
  var fieldName = current.fieldName;
  var value = 'Cell (' + fieldName + ', ' + itemIndex + ')';
  gridView.setValue(itemIndex, fieldName, value);
}

var result = RealGrid.createGrid('realgrid', {
  columns: columns,
  header: {
    height: 40
  },
  display: {
    rowHeight: 36,
    emptyMessage: 'No data to display.'
  },
  footer: {
    height: 40
  },
  stateBar: {
    width: 16
  },
  onInitialized: (grid) => {
    fetch('/data/en/editor_demoData.json')
      .then(response => {
        if (!response.ok) {
          throw new Error('Failed to fetch JSON');
        }
        return response.json();
      })
      .then(data => {
        grid.getDataSource().setRows(data);
      })
      .catch(err => {
        console.error(err);
      });

    grid.onEditSearch = function (grid, index, text) {
      addLog('onEditSearch:' + index.itemIndex + ',' + index.column + ', ' + text);
      var items = CustomerNames.filter(function (str) {
        return str.indexOf(text) === 0;
      });
      addLog(items.toString());
      grid.fillEditSearchItems(index.column, text, items);
    };

    grid.onCopy = function (grid, selection, event) {
      addLog('grid.onCopy');
    };

    grid.onCurrentChanging = function (grid, oldIndex, newIndex) {
      addLog('grid.onCurrentChanging: ' + '(' + oldIndex.itemIndex + ', ' + oldIndex.column + ') => (' + newIndex.itemIndex + ', ' + newIndex.column + ')');
    };

    grid.onCurrentChanged = function (grid, newIndex) {
      addLog('grid.onCurrentChanged: ' + '(' + newIndex.itemIndex + ', ' + newIndex.column + ')');
    };

    grid.onCurrentRowChanged = function (grid, oldRow, newRow) {
      addLog('grid.onCurrentRowChanged: ' + '(' + oldRow + ' => ' + newRow + ')');
    };

    grid.onEditCanceled = function (grid, index) {
      addLog('grid.onEditCanceled driven, edit index=' + JSON.stringify(index));
    };

    grid.onEditChange = function (grid, index, value) {
      addLog('grid.onEditChange driven, ' + index.column + ' at ' + index.dataRow + ' was replaced by value: ' + value);
    };

    grid.onEditCommit = function (grid, index, oldValue, newValue) {
      addLog('grid.onEditCommit driven, ' + oldValue + ' => ' + newValue);
    };

    grid.onEditRowChanged = function (grid, itemIndex, dataRow, field, oldValue, newValue) {
      addLog('grid.onEditRowChanged: ' + oldValue + ' => ' + newValue);
    };

    grid.onGetEditValue = function (grid, index, editResult) {
      addLog('grid.onGetEditValue: ' + JSON.stringify(editResult));
    };

    grid.onCellEdited = function (grid, itemIndex, row, field) {
      addLog('grid.onCellEdited: ' + itemIndex + ', ' + field);
    };

    grid.onHideEditor = function (grid, index) {
      addLog('grid.onHideEditor: ' + index.itemIndex + ',' + index.column);
    };

    grid.onItemEditCancel = function (grid, itemIndex, state) {
      addLog('grid.onItemEditCancel: ' + state);
    };

    grid.onItemEditCanceled = function (grid, itemIndex, state) {
      addLog('grid.onItemEditCanceled: ' + state);
    };

    grid.onPaste = function (grid, index, event) {
      addLog('grid.Paste');
    };

    grid.onPasted = function (grid) {
      addLog('grid.Pasted');
    };

    grid.onEditRowPasted = function (grid, itemIndex, row, fields, oldValues, newValues) {
      addLog('grid.onEditRowPasted: {' + newValues.join() + '}');
    };

    grid.onRowInserting = function (grid, itemIndex, dataRow) {
      addLog('grid.onRowInserting: ' + itemIndex);
      return null;
    };

    grid.onRowsDeleting = function (grid, rows) {
      addLog('grid.onRowsDeleting: ' + rows);
      return null;
    };

    grid.onRowsPasted = function (grid, items) {
      addLog('grid.onRowsPasted' + items);
    };

    grid.onShowEditor = function (grid, index, props, attrs) {
      addLog('grid.onShowEditor: ' + index.itemIndex + ',' + index.column);
    };

    var provider = grid.getDataSource();

    provider.onDataChanged = function (provider) {
      addLog('provider.onDataChanged');
    };

    provider.onRestoreRows = function (provider, rows) {
      addLog('provider.onRestoreRows: ' + rows.join(', '));
    };

    provider.onRowCountChanged = function (provider, newCount) {
      addLog('provider.onRowCountChanged: ' + newCount);
    };

    provider.onRowDeleted = function (provider, row) {
      addLog('provider.onRowDeleted: ' + row);
    };

    provider.onRowDeleting = function (provider, row) {
      addLog('provider.onRowDeleting: ' + row);
      return true;
    };

    provider.onRowInserted = function (provider, row) {
      addLog('provider.onRowInserted');
    };

    provider.onRowInserting = function (provider, row, values) {
      addLog('provider.onRowInserting: ' + row);
      return true;
    };

    provider.onRowListUpdated = function (provider, rows) {
      addLog('provider.onRowListUpdated: ' + rows.join(', '));
    };

    provider.onRowMoved = function (provider, row, newRow) {
      addLog('provider.onRowMoved: ' + row + ' to ' + newRow);
    };

    provider.onRowMoving = function (provider, row, newRow) {
      addLog('provider.onRowMoving: ' + row + ' to ' + newRow);
      return true;
    };

    provider.onRowsDeleted = function (provider, rows) {
      addLog('provider.onRowsDeleted: ' + rows.join(', '));
    };

    provider.onRowsInserted = function (provider, row, count) {
      addLog('provider.onRowsInserted: ' + count + ' rows inserted!');
    };

    provider.onRowsMoved = function (provider, row, count, newRow) {
      addLog('provider.onRowsMoved: ' + count + ' rows moved');
    };

    provider.onRowStateChanged = function (provider, row) {
      addLog('provider.onRowStateChanged: ' + row);
    };

    provider.onRowStatesChanged = function (provider, rows) {
      addLog('provider.onRowStatesChanged: ' + rows.join(','));
    };

    provider.onRowStatesCleared = function (provider) {
      addLog('provider.onRowStatesCleared');
    };

    provider.onRowsUpdated = function (provider, row, count) {
      addLog('provider.onRowsUpdated');
    };

    provider.onRowUpdated = function (provider, row) {
      addLog('provider.onRowUpdated: ' + row);
    };

    provider.onRowUpdating = function (provider, row) {
      addLog('provider.onRowUpdating: ' + row);
      return true;
    };

    provider.onValueChanged = function (provider, row, field) {
      addLog('provider.onValueChanged: ' + row + ' row, ' + field + ' fieldIndex');
    };
  }
}, {
  fields: fields
});

var gridView = result.gridView;
var dataProvider = result.dataProvider;

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