/*global d3*/

function BacktrackVis() {
    var backtrack = {};
    
    backtrack.init = function() {
        this._period = 1;
        this._margin = {top: 20, right: 80, bottom: 30, left: 50};
        this._width = 890 - this._margin.left - this._margin.right;
        this._height = 500 - this._margin.top - this._margin.bottom;
        
        console.log("initializing backtrack vis");
        
        this._svg = d3.select("#backtrack-vis").append("svg")
            .attr("width", this._width + this._margin.left + this._margin.right)
            .attr("height", this._height + this._margin.top + this._margin.bottom)
          .append("g")
            .attr("transform", "translate(" + this._margin.left + "," + this._margin.top + ")");   
        
        
        this._x = d3.scale.linear()
            .range([0, this._width]);
    
        this._y = d3.scale.linear()
            .range([this._height, 0]);
        
        this._xAxis = d3.svg.axis()
            .scale(this._x)
            .orient("bottom");
        
        this._yAxis = d3.svg.axis()
            .scale(this._y)
            .orient("left");
        
        this._x.domain([0, 12]);
        
        this._y.domain([0, 30]);
        
        //convert to minutes
        this._convertTime = function(play) {
            
            var minutes = play.time.minutes;
            var seconds = parseInt(play.time.seconds);
            var total = play.period * 12;
            return total - (minutes + (seconds / 60.0));
        }
        
        this._line_home = d3.svg.line()
            .interpolate("linear")//basis
            .x(function(d) { return this._x(this._convertTime(d)); })
            .y(function(d) { return this._y(d['homeScore']); });
        
        this._line_visitor = d3.svg.line()
            .interpolate("basis")//basis
            .x(function(d) { return this._x(this._convertTime(d)); })
            .y(function(d) { return this._y(d['visitorScore']); });
        
        this._svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + this._height + ")")
            .call(this._xAxis)
        .append("text")
            .attr("x", 850)
            .attr("y", 5)
            .attr("dx", ".71em")
            .style("text-anchor", "end")
            .text("Minutes");
    
        this._svg.append("g")
            .attr("class", "y axis")
            .call(this._yAxis)
        .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("Points");
            
        var team_0 = this._svg.selectAll(".team0")
            .data([])
            .enter().append("g")
            .attr("class", "team0");
            
        var team_1 = this._svg.selectAll(".team1")
            .data([])
            .enter().append("g")
            .attr("class", "team1");
            
        this._circle_tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .html(function(d) {
                var html = "<table><th>Subbed In</th><th>Subbed Out</th>";
                for (var i = 0; i < d.lineupChange.subbed_in.length; i++) {
                    html += "<tr><td>"+ d.lineupChange.subbed_in[i].firstName + " " + d.lineupChange.subbed_in[i].lastName + "</td>"
                    html += "<td>"+ d.lineupChange.subbed_out[i].firstName + " " + d.lineupChange.subbed_out[i].lastName + "</td></tr>"
                }
                html += "</table>";
                return html;
            })
            
        this._path_tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .html(function(d) {
                var html = "<table><th>Lineup</th>";
                for (var i = 0; i < d._current_lineup.length; i++) {
                    html += "<tr><td>"+ d._current_lineup[i].firstName + " " + d._current_lineup[i].lastName+ "</td></tr>"
                }
                html += "</table>";
                return html;
            });
        
        this._svg.call(this._circle_tip);
        this._svg.call(this._path_tip);
            
    }
    
    backtrack.updateAxesIfNecessary = function(gameupdate) {
        var plays = gameupdate.getPBP();
        if (!plays) return;
        
        var lastPlay = plays[plays.length - 1];
        
        if (lastPlay.period > this._period) {    
            this._period = lastPlay.period;
            this.updateAxes();
        }
    }
    
    backtrack.updateAxes = function() {
        console.log("update axes")
        this._x.domain([0, this._period * 12]);
        this._y.domain([0, this._period * 30]);
        
        this._svg.select(".x.axis")
            .transition()
            .duration(1000)
            .ease("sin-in-out")
            .call(this._xAxis);
        this._svg.select(".y.axis")
            .transition()
            .duration(1000)
            .ease("sin-in-out")
            .call(this._yAxis);
    }
    
    backtrack.update = function(gameupdate) {
        var segments = gameupdate.getLineupSegments();
        this.updateAxesIfNecessary(gameupdate);
        
        var team0 = this._svg.selectAll(".team0")
            .data(segments[0]);
            
        var team1 = this._svg.selectAll(".team1")
            .data(segments[1]);
    
        this._svg.selectAll("path")
            .remove();
            
        this._svg.selectAll("circle")
            .remove();
        
        team0.enter().append("path")
            .attr("class", "line")
            .attr("d", (function(d) {return this._line_visitor(d.plays)}).bind(this))
            .style("stroke", "blue")
            .on("mouseover", this._path_tip.show)
            .on("mouseout", this._path_tip.hide)
            
        team0.enter().append("circle")
            .attr("class", "lineup")
            .attr("cx", (function(d) {
                if (!d.lineupChange) return -500;
                return this._x(this._convertTime(d.lineupChange.plays[0]))
            }).bind(this))
            .attr("cy", (function(d) {
                return this._y(d.plays[d.plays.length - 1]['visitorScore'])
            }).bind(this))
            .attr("r", function(d) {
                if (!d.lineupChange) return 5;
                return 2 + 3 * d.lineupChange.subbed_in.length;
            })
            .style("fill", "blue")
            .on("mouseover", this._circle_tip.show)
            .on("mouseout", this._circle_tip.hide)
            
        team1.enter().append("path")
            .attr("class", "line")
            .attr("d", (function(d) {return this._line_home(d.plays)}).bind(this))
            .style("stroke", "red")
            .on("mouseover", this._path_tip.show)
            .on("mouseout", this._path_tip.hide)
            
        team1.enter().append("circle")
            .attr("class", "lineup")
            .attr("cx", (function(d) {
                if (!d.lineupChange) return -500;
                return this._x(this._convertTime(d.lineupChange.plays[0]))
            }).bind(this))
            .attr("cy", (function(d) {
                return this._y(d.plays[d.plays.length - 1]['homeScore'])
            }).bind(this))
            .attr("r", function(d) {
                if (!d.lineupChange) return 5;
                return 2+ 3 * d.lineupChange.subbed_in.length;
            })
            .style("fill", "red")
            .on("mouseover", this._circle_tip.show)
            .on("mouseout", this._circle_tip.hide);
        
        team0.exit().remove();
        team1.exit().remove();
        
    }
    
    return backtrack;
}