import * as React from 'react';
import * as _ from 'lodash';
import { Columns, Column } from 'bloomer';
import * as local from 'localforage';
import { Chart } from './Chart';

export default class ChartLoader extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      chartList: []
    }
    fetch('/config.json')
      .then((response) => response.text())
      .then((jsonStr) => {
        const jsonObj = JSON.parse(jsonStr);
        const chartList = _.get<any>(jsonObj, 'chartList', []);
        this.setState({ chartList });
        local.setItem('config', jsonObj).catch((err: any) => {
          console.error('error occurred when saving config', err);
        });
      })
      .catch((e) => {
        console.error('error occurred when loading config', e);
      });
  }

  public render() {
    return (
      <Columns>
        {this.state.chartList.map((o: any, i: number) =>
          <Column key={i} isSize={3}>
            <Chart csvFile={o.fileName} chartColumn={o.chartColumn} />
          </Column>
        )}
      </Columns>
    )
  }
}
