import {
  PieChart, Pie, ResponsiveContainer, Tooltip, Cell
} from 'recharts';
import * as React from 'react';
import * as _ from 'lodash';
import { Card, CardImage, CardHeader, CardHeaderTitle } from 'bloomer';
const randomColor = require('randomcolor');
import * as Papa from 'papaparse';


export class Chart extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = { data: [] };
    const loaded = (results: any) => {
      const local = this;
      local.setState({
        headers: results.meta.fields,
        data: results.data,
      });
    }
    Papa.parse(this.props.csvFile, {
      header: true,
      download: true,
      skipEmptyLines: true,
      dynamicTyping: true,
      complete: loaded
    });
  }
  public render() {
    const data = this.state.data;
    const countMap = _.countBy(data, (o: any) => _.get<any>(o, this.props.chartColumn))
    const chartData = _.map(_.keys(countMap), (k: any) => {
      return {
        name: k,
        value: countMap[k],
      }
    })
    // const RADIAN = Math.PI / 180;
    // const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index }:any) => {
    //  	const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
    //   const x  = cx + radius * Math.cos(-midAngle * RADIAN);
    //   const y = cy  + radius * Math.sin(-midAngle * RADIAN);
    //
    //   return (
    //     <text x={x} y={y} fill="white" textAnchor='middle' 	dominantBaseline="central">
    //     	{chartData[index].name}
    //     </text>
    //   );
    // };
    const colorMap = this.props.colorMap;
    // const LabeText = (props: any) => {
    //   return (<text>{props.name}</text>);
    // };
    return (
      <Card>
        <CardHeader>
          <CardHeaderTitle className='is-centered'>
            {_.capitalize(this.props.chartColumn)}
          </CardHeaderTitle>
        </CardHeader>
        <CardImage>
          <ResponsiveContainer width="100%" height={300}>
            <PieChart>
              <Pie data={chartData} dataKey='value' outerRadius={100} labelLine={true} label={true}>
                {
                  chartData.map((_0, _1) => {
                    const color = _.get(colorMap, _0.name, randomColor());
                    return (<Cell key={_1} fill={color} />)
                  })
                }
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
        </CardImage>
      </Card>
    )
  }
}
