import React, { Component } from 'react';
import { Doughnut } from 'react-chartjs-2';
import DoughnutChartLegend from 'components/DoughnutChartLegend';

import { formatMoney, formatPercent, formatNumber } from 'lib/i18n';
import palette from 'utils/palette';


let options = {
    cutoutPercentage: 65,
    legend: {
        display: false 
    },
    animate: false,
    animation: {
        animateScale: false,
        animateRotate: false,
    },    
    
};


function renderTooltip(i18n, labels, currency, empty) {
    if (empty) {
        return () => {
            return formatMoney(0, currency, i18n);
        };
    }
    return (tooltipItem, data) => {
        let dataset = data.datasets[tooltipItem.datasetIndex];
        let total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
            return previousValue + currentValue;
        });
        let currentValue = dataset.data[tooltipItem.index];
        return formatMoney(currentValue, currency, i18n) + " (" + formatPercent(currentValue / total * 100, i18n) + ")";
    }
}

export default (props) =>  {
    let { currency, currencySymbol, data, empty, emptyLabel, i18n } = props;
    if (!data) {
        return null;
    }

    let sums = [];
    let labels = [];
    let s = null;
    let colors = ["#BEBEBE"];
    let legend = null;

    if (!empty && Array.isArray(data) && data.length) {
        colors = colors = palette(["#4ec3e0", "#1287ed", "#929ba3", "#678096", "#5beeff"], data.length);
        for (let i = 0; i < data.length; i++) {
            s = data[i];
            labels.push(s.customerName);
            sums.push(s.amount);
        }
        legend = <DoughnutChartLegend labels={ labels } values={ sums } colors={ colors } currency={ currencySymbol || currency } calculatePercents />
    } else {
        labels.push("");
        sums.push(1);

        legend = <DoughnutChartLegend labels={ [emptyLabel] } values={ [0] } percents={ [0] } colors={ colors } currency={ currencySymbol || currency } />
    }

    let chart = {
        labels: labels,
        datasets: [{
            data: sums,
            backgroundColor: colors
        }]
    };

    let tooltip = renderTooltip(i18n, labels, currencySymbol || currency, empty || !Array.isArray(data) || !data.length);

    return (
        <div className="row row-margin-10">
            <div className="col-md-6 p5">
                { legend }
            </div>
            <div className="col-md-6 p10">
                <Doughnut data={ chart } options={ {...options, tooltips: { callbacks: { label: tooltip }} } } redraw={ true }/>
            </div>
        </div>
    );
    
}
