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, gridView) {
  const categories = provider.getFieldValues('year');
  const diVal = provider.getFieldValues('DIncome').map(v => v === undefined ? null : v);

  config = {
    title: {
      text: 'Statistics Korea GNI',
    },
    subtitle: {
      text: 'www.realgrid.com',
    },
    xAxis: {
      categories: categories,
      grid: false,
    },
    yAxis: [
      {
        title: {
          text: 'Income ($)',
        },
        label: {
          suffix: ' $',
          numberSymbols: '',
        },
      },
    ],
    legend: {
      location: 'right',
    },
    series: [
      {
        type: 'line',
        lineType: 'spline',
        name: 'GDP',
        visibleInLegend: false,
        color: '#7cb5ec',
      },
      {
        type: 'line',
        lineType: 'spline',
        name: 'GNI',
        visibleInLegend: false,
        color: '#434348',
      },
      {
        type: 'line',
        lineType: 'spline',
        name: 'PGNI',
        color: '#90ed7d',
        visibleInLegend: false,
      },
      {
        type: 'line',
        lineType: 'spline',
        name: 'DIncome',
        color: '#f7a35c',
        visibleInLegend: false,
      },
      {
        type: 'pie',
        name: 'pie',
        centerX: '15%',
        centerY: '35%',
        visibleInLegend: true,
        radius: '15%',
        pointLabel: {
          visible: true,
          position: 'outside',
          text: '${name}',
        },
        legendByPoint: true,
        data: [
          {
            name: 'GDP',
            color: '#7cb5ec',
            y: gridView.getValue(gridView.getCurrent().itemIndex, 1),
          },
          {
            name: 'GNI',
            color: '#434348',
            y: gridView.getValue(gridView.getCurrent().itemIndex, 2),
          },
          {
            name: 'PGNI',
            color: '#90ed7d',
            y: gridView.getValue(gridView.getCurrent().itemIndex, 3),
          },
          {
            name: 'DIncome',
            color: '#f7a35c',
            y: gridView.getValue(gridView.getCurrent().itemIndex, 4) === undefined 
              ? 0 
              : gridView.getValue(gridView.getCurrent().itemIndex, 4),
          },
        ],
      },
    ],
  };

  rChart = RealChart.createChart(document, 'realchart', config, true, () => {
    setPie(gridView, provider);
  });
}

function setPie(gridView, provider) {
  const index = gridView.getCurrent();
  const rowValue = provider.getJsonRow(index.dataRow);
  const rcData = [];
  Object.keys(rowValue).forEach((k) => {
    let v = rowValue[k];
    if (v === undefined) v = 0;
    if (k === 'Year') return;
    rcData.push(v);
  });

  const pieSeries = rChart.getSeries('pie').data;

  const updateData = pieSeries.map((e, i) => {
    return { name: e.name, color: e.color, y: rcData[i] };
  });

  rChart.getSeries('pie').updateData(updateData);
}

function setCheckValueToChart(values) {
  const mapValues = (values, name) => {
    return values.map((e) => [e.Year, e[name]]);
  };

  if (!rChart) return;
  config.series.forEach((series) => {
    if (series.name !== 'pie') {
      rChart.getSeries(series.name).updateData(mapValues(values, series.name));
    }
  });
}

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
  },
  checkBar: {
    visible: true
  },
  onInitialized: (grid) => {
    fetch('/data/en/총생산소득.json')
      .then(response => response.json())
      .then(data => {
        grid.getDataSource().setRows(data);
        grid.checkRows([0, 2, 4, 6, 8, 10, 12, 14, 16, 18]);
        grid.setFocus();
      });
  },
  onCurrentRowChanged: (grid, index) => {
    setPie(grid, dataProvider);
  },
  onItemChecked: (grid, itemIndex, checked) => {
    const checkItems = grid.getCheckedItems();
    const values = checkItems.map((item) => grid.getValues(item));
    setCheckValueToChart(values);
  },
  onItemsChecked: (grid, items, checked) => {
    const checkItems = grid.getCheckedItems();
    const values = checkItems.map((item) => grid.getValues(item));
    setCheckValueToChart(values);
  },
  onItemAllChecked: (grid, checked) => {
    if (checked) {
      setCheckValueToChart(dataProvider.getJsonRows());
    } else {
      setCheckValueToChart([]);
    }
  }
}, {
  fields
});

dataProvider.onRowCountChanged = function () {
  setRealChart(dataProvider, gridView);
};

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