import React, { Component } from 'react';
import PropTypes from "prop-types";
import * as d3 from 'd3';
import './css/Donut.css';

class Donut extends Component {
    static propTypes = {
        data: PropTypes.array.isRequired
    };

    render(svg) {
        const HIDE_LIMIT = 2;
        d3.select("svg").remove();
        let regions = [];
        let percentage = [];
        let datas = [];
        this.props.data.forEach(element => {
            regions.push(element.region);
            datas.push(element.value);
        });

        let total = datas.reduce((a,b)=>{return a+b},0);
        percentage = datas.map(x => parseInt((x/total)*100));
        console.log("dat tasse");
        console.log(datas);
        
        console.log("percentage");
        console.log(percentage);
        var width = window.screen.width - window.screen.width/2,
            height = window.screen.height - window.screen.height/2;

        var svg = d3.select("div#app")
             .append("svg")
             .attr("width", 3*width)
             .attr("height", 3*height)
             .append("g")

         svg.append("g")
             .attr("class", "slices");
         svg.append("g")
             .attr("class", "percent");
         svg.append("g")
             .attr("class", "labels");
         svg.append("g")
             .attr("class", "lines");
        var radius = Math.min(width, height) / 2;

        var pie = d3.pie()
            .sort(null)
            .value(function (d) {
                return d.value;
            });

        var arc = d3.arc()
            .outerRadius(radius * 0.8)
            .innerRadius(radius * 0.4);

        var outerArc = d3.arc()
            .innerRadius(radius * 0.9)
            .outerRadius(radius * 0.9);

        svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
        var key = function (d) { return d.data.label; };
        var percentkey = function (d, i) { return { idx: i, data: d.data.percent }; };
        var colorRange = [];
        
        for(let i=0;i<regions.length;i++){
            colorRange.push(d3.interpolateBlues((i*1.0)/(regions.length+10)));
        }
        var color = d3.scaleOrdinal().range(colorRange).domain(regions);

        function randomData() {
            var labels = color.domain();
            console.log(labels);
            return labels.map(function (label, i) {
                return { label: label, value: datas[i], percent: percentage[i] }
            });
        }

        function changeinit(data) {
            /* ------- PIE SLICES -------*/
            var slice = svg.select(".slices").selectAll("path.slice")
                .data(pie(data), key);

            slice.enter()
                .insert("path")
                .style("fill", function (d, i) { return color(i); })
                .attr("class", "slice")
                .transition().duration(1000)
                .attrTween("d", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        return arc(interpolate(t));
                    };
                })



            slice.exit()
                .remove();

            /* ------- TEXT LABELS -------*/
            var percent = svg.select(".percent").selectAll("text")
                .data(pie(data), percentkey.data);

            percent.enter()
                .append("text")
                .attr("dy", ".35em")
                .text(function (d) {
                    if(d.data.percent > HIDE_LIMIT){
                        return d.data.percent + "%";
                    }
                    else {
                        return " ";
                    }
                }).transition().duration(1000)
                .attrTween("transform", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        var d2 = interpolate(t);
                        var pos = arc.centroid(d2);
                        //pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                        return "translate(" + pos + ")";
                    };
                })

            percent.exit()
                .remove();

            var text = svg.select(".labels").selectAll("text")
                .data(pie(data), key);




            function midAngle(d) {
                return d.startAngle + (d.endAngle - d.startAngle) / 2;
            }
            text.enter()
                .append("text")
                .attr("dy", ".35em")
                .text(function (d) {
                    if(d.data.percent > HIDE_LIMIT){
                        return d.data.label;
                    }
                    else {
                        return " ";
                    }
                }).transition().duration(1000)
                .attrTween("transform", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        var d2 = interpolate(t);
                        var pos = outerArc.centroid(d2);
                        pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                        return "translate(" + pos + ")";
                    };
                })

                .styleTween("text-anchor", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        var d2 = interpolate(t);
                        return midAngle(d2) < Math.PI ? "start" : "end";
                    };
                });

            text.exit()
                .remove();
            /* ------- SLICE TO TEXT POLYLINES -------*/

            var polyline = svg.select(".lines").selectAll("polyline")
                .data(pie(data), key);

            polyline.enter()
                .append("polyline").transition().duration(1000)
                .attrTween("points", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    if(d.data.percent < HIDE_LIMIT){
                        return function(t){
                            return [[0,0],[0,0],[0,0]];
                        }
                    }
                    else {
                        return function (t) {
                            console.log(t);
                            var d2 = interpolate(t);
                            var pos = outerArc.centroid(d2);
                            pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
                            return [arc.centroid(d2), outerArc.centroid(d2), pos];
                        };
                    }
                    
                });

            polyline.exit()
                .remove();
        };

        function changeupdate(data) {

            /* ------- PIE SLICES -------*/
            var slice = svg.select(".slices").selectAll("path.slice")
                .data(pie(data), key);

            slice.enter()
                .insert("path")
                .style("fill", function (d, i) { return color(i); })
                .attr("class", "slice");

            slice.transition().duration(1000)
                .attrTween("d", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        return arc(interpolate(t));
                    };
                })



            slice.exit()
                .remove();

            /* ------- TEXT LABELS -------*/
            var percent = svg.select(".percent").selectAll("text")
                .data(pie(data), percentkey.data);

            percent.enter()
                .append("text")
                .attr("dy", ".35em")
                .text(function (d) {
                    if(d.data.percent > HIDE_LIMIT){
                        return d.data.percent+"%";
                    }
                    else {
                        return " ";
                    }
                });

            percent.transition().duration(1000)
                .attrTween("transform", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        var d2 = interpolate(t);
                        var pos = arc.centroid(d2);
                        //pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                        return "translate(" + pos + ")";
                    };
                })

            percent.exit()
                .remove();

            var text = svg.select(".labels").selectAll("text")
                .data(pie(data), key);




            function midAngle(d) {
                return d.startAngle + (d.endAngle - d.startAngle) / 2;
            }
            text.enter()
                .append("text")
                .attr("dy", ".35em")
                .text(function (d) {
                    if(d.data.percent > HIDE_LIMIT){
                        return d.data.label;
                    }
                    else {
                        return " ";
                    }
                });

            text.transition().duration(1000)
                .attrTween("transform", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        var d2 = interpolate(t);
                        var pos = outerArc.centroid(d2);
                        pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
                        return "translate(" + pos + ")";
                    };
                })

                .styleTween("text-anchor", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    return function (t) {
                        var d2 = interpolate(t);
                        return midAngle(d2) < Math.PI ? "start" : "end";
                    };
                });

            text.exit()
                .remove();
            /* ------- SLICE TO TEXT POLYLINES -------*/

            var polyline = svg.select(".lines").selectAll("polyline")
                .data(pie(data), key);

            polyline.enter()
                .append("polyline");
            polyline.transition().duration(1000)
                .attrTween("points", function (d) {
                    this._current = this._current || d;
                    var interpolate = d3.interpolate(this._current, d);
                    this._current = interpolate(0);
                    if(d.data.percent < HIDE_LIMIT){
                        return function(t){
                            return [[0,0],[0,0],[0,0]];
                        }
                    }
                    else {
                        return function (t) {
                            console.log(t);
                            var d2 = interpolate(t);
                            var pos = outerArc.centroid(d2);
                            pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
                            return [arc.centroid(d2), outerArc.centroid(d2), pos];
                        };
                    }
                });

            polyline.exit()
                .remove();
        };

        d3.select(".randomize")
            .on("click", function () {
                color = d3.scaleOrdinal()
                    .range(colorRange)
                    .domain(regions);
                changeupdate(randomData());
            });
        changeinit(randomData());
        return <div id="app">

        </div>;
    }
}


export default Donut;