// Reference: https://d3-graph-gallery.com/graph/lollipop_button_data_csv.html
// The interactive dumbbell chart take inspirations from this interactive lollipop chart example

const moneyJ = document.getElementsByClassName("moneyJap")[0];
const moneyA = document.getElementsByClassName("moneyAus")[0];
const moneyS = document.getElementsByClassName("moneySwit")[0];
const moneyC = document.getElementsByClassName("moneyCan")[0];
const moneyB = document.getElementsByClassName("moneyBri")[0];
const moneyU = document.getElementsByClassName("moneyUni")[0];
const moneyT = document.getElementsByClassName("moneyTur")[0];


const minAge = 55
const rW = 8
const rH = 8

// set the dimensions and margins of the graph
const mySvg = d3.select("#viz_dumbbell"),
    margin_dumbbell = { top: 0, right: 80, bottom: 380, left: 100 },
    width_dumbbell = +mySvg.attr("width") - margin_dumbbell.left - margin_dumbbell.right,
    height_dumbbell = +mySvg.attr("height") - margin_dumbbell.top - margin_dumbbell.bottom;

// append the svg object to the body of the page
const svg_dumbbell = d3.select("#viz_dumbbell")
    .append("svg")
    .attr("width", width_dumbbell + margin_dumbbell.left + margin_dumbbell.right)
    .attr("height", height_dumbbell + margin_dumbbell.top + margin_dumbbell.bottom)
    .append("g")
    .attr("transform", `translate(${margin_dumbbell.left}, ${margin_dumbbell.top})`);


// Initialize the X axis
const x = d3.scaleBand()
    .range([width_dumbbell, 0])
    .padding(1);
const xAxis = svg_dumbbell.append("g")
    .attr("class", "x axis")
    .attr("transform", `translate(0, ${height_dumbbell})`)

// Initialize the Y axis
const y = d3.scaleLinear()
    .range([height_dumbbell, 0]);
const yAxis = svg_dumbbell.append("g")
    .attr("class", "y axis")
// .attr("class", "myYaxis")


// A function that create / update the plot for a given variable:
function update(selectedVar, selectedTime, selectedRate, moneyBag_Jap, moneyBag_Aus, moneyBag_Swit, moneyBag_Can, moneyBag_Bri, moneyBag_Uni, moneyBag_Tur, selectedSpending) {


    d3.csv("./csvFile/dumbbell.csv", function (d) {

        return d;
    }, function (error, data) {

        if (error) throw error;

        data.sort(function (a, b) {
            // range is flipped, so it ascends from bottom of chart
            return d3.ascending(+a.end_lexp, +b.end_lexp);
        });
        // X axis
        x.domain(data.map(function (d) { return d.country; }))
        xAxis.transition().duration(1000).call(d3.axisBottom(x))

        // Add Y axis
        // y.domain([minAge, d3.max(data, function (d) { return d.end_lexp; })]);
        y.domain([minAge, 88]);
        yAxis.transition().duration(1000).call(d3.axisLeft(y));


        const gradient = svg_dumbbell.append("svg:defs")
            .append("svg:linearGradient")
            .attr("id", "gradient")
            .attr("x1", "0%")
            .attr("y1", "0%")
            .attr("x2", "0%")
            .attr("y2", "100%")
            .attr("spreadMethod", "pad");

        gradient.append("svg:stop")
            .attr("class", "begin")
            .attr("offset", "0%");

        gradient.append("svg:stop")
            .attr("class", "end")
            .attr("offset", "100%");

        // variable u: map data to existing rect
        const j = svg_dumbbell.selectAll(".myLine")
            .data(data)


        // update rect
        j
            .enter()
            .append("rect")
            .attr("class", "myLine")
            .merge(j)
            .transition()
            .duration(1000)
            .attr("x", function (d) { return x(d.country) - 2; })

            .attr("y", function (d) { return y(d[selectedVar]) })
            .attr("width", 5)
            .attr("height", function (d) { return y(d.start_lexp) - y(d[selectedVar]) })

            .attr("fill", "url(#gradient)")
            .attr("stroke-width", 3)
        // console.log(function (d) { return + (d[selectedVar]) });



        var tooltip_dumb = d3
            .select("#viz_dumbbell")
            .append("div")
            .style("opacity", 0)
            // .style("border", "1px solid #313639;")
            .attr("class", "tooltipDumb");

        // .style("visibility", "visible");

        var showOriginal = function (d) {
            tooltip_dumb.transition().duration(100);
            const dumbMessage = `${d.country}<br/>life Expectancy: ${d.start_lexp} `;
            tooltip_dumb
                .style("width", "8vw")
                .style("height", "3vh")
                .style("font-size", "1rem")
                .style("opacity", 1)
                .html(dumbMessage)
                .style("left", d3.mouse(this)[0] + 590 + "px")
                .style("top", d3.mouse(this)[1] + 1150 + "px");
        }
        var showLifeGrowth = function (d) {
            tooltip_dumb.transition().duration(100);
            var growthMessage = `${d.country}<br/>life Expectancy: ${d[selectedVar]}`;
            tooltip_dumb
                .style("width", "8vw")
                .style("height", "3vh")
                .style("font-size", "1rem")
                .style("opacity", 1)
                .html(growthMessage)
                .style("left", d3.mouse(this)[0] + 590 + "px")
                .style("top", d3.mouse(this)[1] + 1150 + "px");
        }
        // var moveTooltipDumb = function (d) {
        //     tooltip_dumb
        //         .style("left", d3.mouse(this)[0] + 20 + "px")
        //         .style("top", d3.mouse(this)[1] + 100 + "px");
        // }
        var hideTooltipDumb = function (d) {
            tooltip_dumb.transition().duration(100).style("opacity", 0);
        }

        // variable u: map data to existing circle
        const higherC = svg_dumbbell.selectAll("circle")
            .data(data)
            .on("mouseover", showLifeGrowth)
            .on("mousemove", showLifeGrowth)
            .on("mouseleave", hideTooltipDumb)
        // update bars
        higherC
            .enter()
            .append("circle")
            .merge(higherC)
            .transition()
            .duration(1000)
            .attr("cx", function (d) { return x(d.country); })
            .attr("cy", function (d) { return y(d[selectedVar]); })
            .attr("r", 8)
            // .style("fill", "url(#gradient)")
            .attr("fill", "#FFC700")


        const lowerC = svg_dumbbell.selectAll("ellipse")
            .data(data)
            .on("mouseover", showOriginal)
            .on("mousemove", showOriginal)
            .on("mouseleave", hideTooltipDumb)
        // update bars
        lowerC
            .enter()
            .append("ellipse")
            .merge(lowerC)
            .transition()
            .duration(1000)
            .attr("cx", (d) => x(d.country))
            .attr("cy", (d) => y(d["start_lexp"]))
            .attr("rx", rW)
            .attr("ry", rH)
            .attr("fill", "#FF4397");



        d3.selectAll(".higher").remove();
        const higherT = svg_dumbbell.selectAll(".higher")
            .data(data)

        higherT
            .enter()
            .append("text")
            .merge(higherT)
            // .transition()
            // .duration(200)
            .attr("class", "higher")
            .attr("x", (d) => x(d.country))
            .attr("y", function (d) { return y(d[selectedVar]); })
            .attr("dy", "-2em")
            .attr("dx", -9)
            .text(function (d) { console.log("The life expectancy in " + d.country + " is " + (d[selectedVar])); console.log("Change Rate of Life Expectancy in " + d.country + " is " + d[selectedRate]); return (d[selectedRate]) + " %"; })


        //append spending ($) of different countries
        const moneyText = svg_dumbbell.selectAll(".moneyText")
            .data(data)
        moneyText
            .enter()
            .append("text")
            .merge(moneyText)
            // .transition()
            // .duration(200)
            .attr("class", "moneyText")
            .attr("x", (d) => x(d.country) - 15)
            .attr("y", function (d) { return height_dumbbell + 110; })
            .attr("dy", "-2em")
            .attr("dx", -9)
            .text(function (d) { console.log("Spending in " + d.country + " is " + (d[selectedSpending])); return "$ " + (d[selectedSpending]); })
        // .text(function (d) { return "$ " + (d.end_time); })


        //append spending ($) of different countries
        const legendEnd = svg_dumbbell.selectAll(".legendE")
            .data(data)
        legendEnd
            .enter()
            .append("text")
            .merge(legendEnd)
            // .transition()
            // .duration(200)
            .attr("class", "legendE")
            .attr("x", width_dumbbell * 0.39)
            .attr("y", 862)
            .attr("dy", "-2em")
            .attr("dx", -9)
            .attr("fill", '#545454')

            .text(function (d) { return (d[selectedTime]); })

        const legendStart = svg_dumbbell.selectAll(".legendS")
            .data(data)
        legendStart
            .enter()
            .append("text")
            .merge(legendStart)
            // .transition()
            // .duration(200)
            .attr("class", "legendS")
            .attr("x", width_dumbbell * 0.24)
            .attr("y", 862)
            .attr("dy", "-2em")
            .attr("dx", -9)
            .attr("fill", '#545454')
            .text(function (d) { return (d.start_time); })


        svg_dumbbell.append('circle')
            .attr('cx', width_dumbbell * 0.35)
            .attr('cy', 830)
            .attr('r', 8)
            .attr('height', 70)
            .attr('width', 180)
            .attr('fill', '#FFC700')
            // .attr('stroke-width', 1)
            .attr('margin', '0')

        svg_dumbbell.append('circle')
            .attr('cx', width_dumbbell * 0.2)
            .attr('cy', 830)
            .attr('r', 8)
            .attr('height', 70)
            .attr('width', 180)
            .attr('fill', '#FF4397')
            // .attr('stroke-width', 1)
            .attr('margin', '0')


        // svg_dumbbell.append('text')
        //     .data(data)
        //     // .attr("text-anchor", middle)
        //     .attr("x", width_dumbbell * 0.1)
        //     .attr("y", -52)
        //     .attr("font-family", "poppins")
        //     .attr("font-size", "22px")
        //     .attr("fill", '#6968A0')
        //     .attr("font-weight", "bold")
        //     // .attr("font", "sans-serif")
        //     .text("The growth in healthcare spending and life expectancy in 7 countries")

        // // text.setAttributeNS(null, 'style', 'text-anchor: middle;');


        // //title circle
        // svg_dumbbell.append('circle')
        //     .attr('cx', width_dumbbell * 0.49)
        //     .attr('cy', -20)
        //     .attr('r', 5)
        //     .attr('height', 70)
        //     .attr('width', 180)
        //     .attr('fill', '#6968A0')
        //     // .attr('stroke-width', 1)
        //     .attr('margin', '0')



        // svg_dumbbell.append('rect')
        //     // .data(data)
        //     .attr("x", width_dumbbell * 0.2)
        //     .attr("y", -20)
        //     .attr("width", 250)
        //     .attr("height", 3)
        //     .attr("fill", "#6968A0")
        //     .attr("stroke-width", 5)

        // svg_dumbbell.append('rect')
        //     // .data(data)
        //     .attr("x", width_dumbbell * 0.54)
        //     .attr("y", -20)
        //     .attr("width", 250)
        //     .attr("height", 3)
        //     .attr("fill", "#6968A0")
        //     .attr("stroke-width", 5)

        //Japan
        moneyJ.animate({ height: [moneyBag_Jap] + "px" }, 1000);

        // console.log("Japan bag height: " + [moneyBag_Jap]);

        // Australia
        moneyA.animate({ height: [moneyBag_Aus] + "px" }, 1000);
        // return moneyBag_Aus;
        // console.log("Australia bag height: " + [moneyBag_Aus]);


        // Switzerland
        moneyS.animate({ height: [moneyBag_Swit] + "px" }, 1000);

        // Canada
        moneyC.animate({ height: [moneyBag_Can] + "px" }, 1000);
        // UK
        moneyB.animate({ height: [moneyBag_Bri] + "px" }, 1000);
        // US
        moneyU.animate({ height: [moneyBag_Uni] + "px" }, 1000);
        // Turkey
        moneyT.animate({ height: [moneyBag_Tur] + "px" }, 1000);



        var goJan = moneyBag_Jap;
        // console.log("test jap num: " + goJan);
        var goAus = moneyBag_Aus;
        var goSwit = moneyBag_Swit;
        var goCan = moneyBag_Can;
        var goBri = moneyBag_Bri;
        var goUni = moneyBag_Uni;
        var goTur = moneyBag_Tur;

        // console.log("test: " + testLife)
        go(goJan, goAus, goSwit, goCan, goBri, goUni, goTur);
        setTimeout(go, 1000)



    })
}


// }


function go(goJan, goAus, goSwit, goCan, goBri, goUni, goTur) {

    moneyJ.style.height = goJan;
    // console.log("moneyJ height: " + moneyJ.style.height);

    moneyA.style.height = goAus;
    // console.log("moneyA height: " + moneyA.style.height);

    moneyS.style.height = goSwit;
    // console.log("moneyS height: " + moneyS.style.height);

    moneyC.style.height = goCan;
    // console.log("moneyS height: " + moneyS.style.height);

    moneyB.style.height = goBri;
    // console.log("moneyS height: " + moneyS.style.height);

    moneyU.style.height = goUni;
    // console.log("moneyS height: " + moneyS.style.height);

    moneyT.style.height = goTur;
    // console.log("moneyS height: " + moneyS.style.height);


}
// Initialize plot
// update 1985's data
update('progress_1985', 'time_1985', 'rate_1985', '60.5', '60.2', '58.2', '57.8', '61.6', '54.3', '68', 'money_1985');

