const fields = [
  {
    fieldName: 'Year',
    dataType: 'text',
  },
  {
    fieldName: 'GDP',
    dataType: 'number',
  },
  {
    fieldName: 'GNI',
    dataType: 'number',
  },
  {
    fieldName: 'PGNI',
    dataType: 'number',
  },
  {
    fieldName: 'DIncome',
    dataType: 'number',
  },
];

const columns = [
  {
    name: 'Year',
    fieldName: 'Year',
    width: '80',
    header: {
      text: 'Year',
    },
  },
  {
    name: 'GDP',
    fieldName: 'GDP',
    width: '160',
    header: {
      text: 'GDP ($100 milion)',
    },
    styleName: 'column-background1',
  },
  {
    name: 'GNI',
    fieldName: 'GNI',
    width: '160',
    header: {
      text: 'GNI ($100 milion)',
    },
    styleName: 'column-background2',
  },
  {
    name: 'PGNI',
    fieldName: 'PGNI',
    width: '160',
    header: {
      text: 'PGNI ($)',
    },
    styleName: 'column-background3',
  },
  {
    name: 'DIncome',
    fieldName: 'DIncome',
    width: '160',
    header: {
      text: 'DIncome ($)',
    },
    styleName: 'column-background4',
  },
];

let rChart;
let config;

function setRealChart(provider) {
  const categories = provider.getFieldValues('year');
  const diVal = provider.getFieldValues('DIncome').map(v => v === undefined ? 0 : v);

  config = {
    title: {
      text: 'Statistics Korea GNI',
    },
    subtitle: {
      text: 'www.realgrid.com',
    },
    options: {},
    xAxis: {
      categories: categories,
    },
    yAxis: [
      {
        title: {
          text: 'Income ($)',
        },
        label: {
          suffix: ' $',
          numberSymbols: '',
        },
      },
    ],
    series: [
      {
        name: 'GDP',
        data: provider.getFieldValues('GDP'),
        color: '#7cb5ec',
      },
      {
        name: 'GNI',
        data: provider.getFieldValues('GNI'),
        color: '#434348',
      },
      {
        name: 'PGNI',
        data: provider.getFieldValues('PGNI'),
        color: '#90ed7d',
      },
      {
        name: 'DIncome',
        data: diVal,
        color: '#f7a35c',
      },
    ],
  };

  rChart = RealChart.createChart(document, 'realchart', config);
}

function setFilter(gridView, dataProvider) {
  const filters = [];
  const vals = dataProvider.getDistinctValues('year');
  vals.forEach((v) => {
    const filter = {
      name: v,
      criteria: "value = '" + v + "'",
    };
    filters.push(filter);
  });

  const col = gridView.columnByName('Year');
  col.filters = filters;
  gridView.setColumn(col);
}

const { gridView, dataProvider } = RealGrid.createGrid('realgrid', {
  columns,
  header: {
    height: 40
  },
  display: {
    rowHeight: 36,
    emptyMessage: 'No data to display.'
  },
  edit: {
    insertable: true,
    appendable: true
  },
  footer: {
    height: 40
  },
  stateBar: {
    width: 16
  },
  onInitialized: (grid) => {
    fetch('/data/en/총생산소득.json')
      .then(response => response.json())
      .then(data => {
        grid.getDataSource().setRows(data);
        setTimeout(() => setFilter(grid, grid.getDataSource()), 300);
      });
  },
  onFilteringChanged: (grid) => {
    const count = grid.getItemCount();
    const jArr = [];
    for (let i = 0; i < count; i++) {
      const jObj = grid.getValues(i);
      if (!jObj.Year) jObj.Year = null;
      jArr.push(jObj);
    }
    if (!config) return;
    config.series.forEach((series) => {
      const updateData = jArr.map((val) => {
        return [val.Year, val[series.name]];
      });
      rChart.getSeries(series.name).updateData(updateData);
    });
  },
  onDataLoadComplated: (grid) => {
    setRealChart(dataProvider);
  }
}, {
  fields
});

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