let intro_svg;

function type(d, i, columns) {
    for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
    d.total = t;
    return d;
}

function make_intro_svg() {
    "use strict";
    let maxValue;
    let yAxis, yAxisG, dataArea, dataLine;
    let margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 200
    };

    let width = 1320 - margin.left - margin.right;
    let height = 600 - margin.top - margin.bottom;

    let x = d3.scaleTime().range([0, width]);
    let y = d3.scaleLinear().range([height, 0]);

    let area = d3.area()
        .x(function (d) { return x(d.date) })
        .y0(height)
        .y1(function (d) { return y(d.volume) });

    let valueline = d3.line()
        .x(function (d) { return x(d.date) })
        .y(function (d) { return y(d.volume) });

    intro_svg = d3.select('svg#intro')
        .attr('width', width + margin.left + margin.bottom)
        .attr('height', height + margin.top + margin.bottom)
        .append('g')
        .attr('transform', `translate(${margin.left},${margin.top})`);

    d3.csv('volume.csv', function (d) {
        return {
            date: new Date(d.date),
            volume: +d.volume, // make sure volume is numeric
        }
    }, function (d) {
        plotArea(d);
    });


    function plotArea(data) {
        "use strict";
        x.domain(d3.extent(data, d => d.date));
        maxValue = d3.max(data, d=> d.volume);
        y.domain([0, maxValue]);

        dataArea = intro_svg.append('path')
            .data([data])
            .attr('class', 'area hidden')
            .attr('d', area);

        dataLine = intro_svg.append('path')
            .data([data])
            .attr('class', 'line')
            .attr('d', valueline);

        let totalLength = dataArea.node().getTotalLength();

        dataLine.attr("stroke-dasharray", totalLength + " " + totalLength).attr("stroke-dashoffset", totalLength);
        dataArea.attr("stroke-dasharray", totalLength + " " + totalLength).attr("stroke-dashoffset", totalLength);

        intro_svg.append('g')
            .attr("transform", `translate(0, ${height})`)
            .call(d3.axisBottom(x));

        yAxis = d3.axisLeft(y);

        yAxisG = intro_svg.append('g')
            .attr('class', 'yaxis')
            .call(yAxis);
    }

    d3.select("#growth").on('impress:stepenter', function () {
        dataLine.transition().ease(d3.easeLinear).duration(10000).attr('stroke-dashoffset', 0)
            .on('end', function () {
                dataArea.classed('hidden', false);
            });
    });
}

function make_bar_chart() {
    let margin = {top: 20, right: 60, bottom: 60, left: 40};

    let width = 1320 - margin.left - margin.right;
    let height = 600 - margin.top - margin.bottom;

    let svg = d3.select("svg#composition"),
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.attr('width', width + margin.left + margin.bottom)
       .attr('height', height + margin.top + margin.bottom);

    let x = d3.scaleBand()
        .rangeRound([0, width - margin.right])
        .padding(0.1)
        .align(0.1);

    let y = d3.scaleLinear()
        .rangeRound([height, 0]);

    let z = d3.scaleOrdinal()
        .range(["#e6194b", "#3cb44b", "#ffe119", "#0082c8", "#f58231", "#911eb4", "#46f0f0", "#f032e6", "#d2f53c",
            "#fabebe", "#008080", "#e6beff", "#aa6e28", "#fffac8", "#800000", "#aaffc3", "#808000", "#ffd8b1",
            "#000080", "#808080", "#FFFFFF", "#000000"]);

    let stack = d3.stack()
        .offset(d3.stackOffsetExpand);

    d3.csv("volume_per_coin_per_month.csv", type, function(error, data) {
        if (error) throw error;

        x.domain(data.map(function(d) { return d.date; }));
        z.domain(data.columns.slice(1));

        let serie = g.selectAll(".serie")
            .data(stack.keys(data.columns.slice(1))(data))
            .enter().append("g")
            .attr("class", "serie")
            .attr("fill", function(d) { return z(d.key); });

        serie.selectAll("rect")
            .data(function(d) { return d; })
            .enter().append("rect")
            .attr("x", function(d) { return x(d.data.date); })
            .attr("y", function(d) { return y(d[1]); })
            .attr("height", function(d) { return y(d[0]) - y(d[1]); })
            .attr("width", x.bandwidth());

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x))
            .selectAll("text")
                .attr("y", 0)
                .attr("x", 9)
                .attr("dy", ".35em")
                .attr("transform", "rotate(90)")
                .style("text-anchor", "start");

        g.append("g")
            .attr("class", "axis axis--y")
            .call(d3.axisLeft(y).ticks(10, "%"));

        let legend = serie.append("g")
            .attr("class", "legend")
            .attr("transform", function(d) {
                d = d[d.length - 1];
                return "translate(" + (x(d.data.date) + x.bandwidth()) + "," + ((y(d[0]) + y(d[1])) / 2) + ")";
            });

        legend.append("line")
            .attr("x1", -6)
            .attr("x2", 6)
            .attr("stroke", "#000");

        legend.append("text")
            .attr("x", 9)
            .attr("dy", "0.35em")
            .attr("fill", "#000")
            .style("font", "10px sans-serif")
            .text(function(d) { return d.key; });
    });
}

function make_pizza_per_btc() {
    let margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    let parseDate = d3.timeParse("%Y-%m-%d");

    let x = d3.scaleTime()
        .range([0, width]);

    let y = d3.scaleLinear()
        .range([height, 0]);

    let xAxis = d3.axisBottom()
        .scale(x);

    let yAxis = d3.axisLeft()
        .scale(y);

    let line1 = d3.area()
        .curve(d3.curveBasis)
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.low); });

    let line2 = d3.area()
        .curve(d3.curveBasis)
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.high); });

    let area = d3.area()
        .curve(d3.curveBasis)
        .x(function(d) { return x(d.date); })
        .y1(function(d) { return y(d.low); });

    let svg = d3.select("svg#pizza-per-btc-svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.csv("pizzas_per_btc.csv", function(error, data) {
        if (error) throw error;

        data.forEach(function(d) {
            d.date = parseDate(d.date);
            d.low= +d.low;
            d.high = +d.high;
        });

        console.log(data);

        x.domain(d3.extent(data, function(d) { return d.date; }));

        y.domain([
            d3.min(data, function(d) { return d.low }),
            d3.max(data, function(d) { return d.high; })
        ]);

        svg.datum(data);

        svg.append("clipPath")
            .attr("id", "clip-below")
            .append("path")
            .attr("d", area.y0(height));

        svg.append("clipPath")
            .attr("id", "clip-above")
            .append("path")
            .attr("d", area.y0(0));

        svg.append("path")
            .attr("class", "area between")
            .attr("clip-path", "url(#clip-above)")
            .attr("d", area.y0(function(d) { return y(d.high); }));

        svg.append("path")
            .attr("class", "line1")
            .attr("d", line1);

        svg.append("path")
            .attr("class", "line2")
            .attr("d", line2);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("# of pizza's per BTC");
    });
}

make_intro_svg();

make_bar_chart();

make_pizza_per_btc();
