function LineupChange(pbp, index) {
    var lineupChange = {};
    
    var firstSubstitution = pbp[index];
    var teamId = firstSubstitution.players[0].teamId;
    
    lineupChange.plays = [firstSubstitution];
    lineupChange.subbed_in = [firstSubstitution.players[0]];
    lineupChange.subbed_out = [firstSubstitution.players[1]];
    
    lineupChange.addPlay = function(play) {
        this.plays.push(play);
        this.subbed_in.push(play.players[0]);
        this.subbed_out.push(play.players[1]);
    }
    
    var seek = index + 1;
    while (seek < pbp.length 
        && pbp[seek].playEvent.playEventId == 10
        && pbp[seek].players[0]["teamId"] == teamId) {
            lineupChange.addPlay(pbp[seek]);
            seek += 1;
    }
    
    lineupChange.numPlays = function() {
        return this.plays.length;
    }
    
    lineupChange.getName = function(player) {
        return player.firstName + " " + player.lastName;
    }
    
    lineupChange.tip = function() {
        var str = "";
        for (var i = 0; i < this.subbed_in.length - 1; i++) {
            str += this.getName(this.subbed_in[i]) + " and ";
        }
        str += this.getName(this.subbed_in[this.subbed_in.length - 1]);
        
        str += " sub in for "
        for (var i = 0; i < this.subbed_out.length - 1; i++) {
            str += this.getName(this.subbed_out[i]) + " and ";
        }
        str += this.getName(this.subbed_out[this.subbed_out.length - 1]);
        return str;
    }
    return lineupChange;
}

function LineupSegment(play, current_lineup) {
    var segment = {};
    segment.plays = [];
    segment.allPlays = [];
    segment._current_lineup = current_lineup;
    
    if (current_lineup) segment.num_players = current_lineup.length;
    
    if (typeof play != 'undefined' && play != null) {
        segment.plays.push(play);
    }
    segment.lineupChange = null;
    
    segment.isThreePointMade = function(play) {
        return (typeof play.shotAttemptPoints != 'undefined'
            && play.shotAttemptPoints == 3 
            && play.pointsScored == 3)
    }
    
    segment.isTurnover = function(play) {
        return (play.playEvent.playEventId == 7);
    }
    
    segment.finalizeStats = function(team_index) {
        this.storePointsScored(team_index)
        this.threePointsMade = 0;
        this.turnovers = 0;
        for (var i = 0; i < this.allPlays.length; i++) {
            var play = this.allPlays[i];
            if (this.isThreePointMade(play)) this.threePointsMade += 1;
            if (this.isTurnover(play)) this.turnovers += 1;
        }
    }
    
    segment.storePointsScored = function(team_index) {
        var key;
        if (team_index == 0) key = "visitorScore"
        else key = "homeScore"
        
        var first_play = this.plays[0];
        var last_play = this.plays[this.plays.length - 1];
        this.pointsScored = last_play[key] - first_play[key];
    }
    
    segment.addPlay = function(play) {
        if (typeof play.pointsScored != 'undefined') {
            this.plays.push(play);
        }
        this.allPlays.push(play);
    }
    
    return segment;
}

function printLineup(lineup) {
    if (!lineup) {
        console.log("no lineup");
        return;
    }
    var text = "";
    for (var i = 0; i < lineup.length; i++) {
        text += lineup[i].firstName + " " + lineup[i].lastName + ", ";
    }
    console.log(text);
}

function DynamicLineups(startingLineupsXXX) {
    var dynamicLineups = {};
    
    dynamicLineups._lineups = startingLineupsXXX;
    
    dynamicLineups.updateLineup = function(team_index, lineupChange) {
        
        for (var i = 0; i < lineupChange.subbed_out.length; i++) {
            var to_remove = lineupChange.subbed_out[i];
            for (var j = 0; j < this._lineups[team_index].length; j++) {
                var curr_player = this._lineups[team_index][j];
                if (curr_player.playerId == to_remove.playerId) {
                    var removed = this._lineups[team_index].splice(j, 1);
                    break;
                }
            }
        }
        
        for (var i = 0; i < lineupChange.subbed_in.length; i++) {
            var to_add = lineupChange.subbed_in[i];
            this._lineups[team_index].push(to_add);
        }
    }
    
    dynamicLineups.getLineup = function(team_index) {
        return this._lineups[team_index].slice(0);
    }
    
    dynamicLineups.setActualStarters = function(team_index, actual_starters) {
        console.log("setting actual starters", JSON.stringify(actual_starters))
        this._lineups[team_index] = actual_starters;
    }
    
    return dynamicLineups;
}

function injestStartingLineup(pbp, teammap) {
    var starters = [[], []]
    for (var i = 0; i < 10; i++) {
        var play = pbp[i];
        var team_index = teammap[play.players[0].teamId];
        starters[team_index].push(play.players[0]);
    }
    //console.log("injested starting lineup", starters[0].length, JSON.stringify(starters[0]))
    return starters;
}

function LineupSegmentList(pbp, teammap, startinglineupdata) {
    var lineupSegments = [[],[]];
    var current_lineups = DynamicLineups(injestStartingLineup(pbp, teammap));
    var current_segments = [LineupSegment(null, current_lineups.getLineup(0)), LineupSegment(null, current_lineups.getLineup(1))];
    var keeper = {};
    
    var index = 10;
    while (index < pbp.length) {
        var play = pbp[index];
        if (play.playEvent.playEventId == 14) {
            
            /*//console.log(startinglineupdata)
            if (startinglineupdata && startinglineupdata[play.period]) {
                
                //var lineupChange = LineupChange(pbp, index);
                
                //create a lineupchange based on the difference
                var actual_starters_0 = startinglineupdata[play.period][0];
                current_lineups.setActualStarters(0, actual_starters_0);
                
                var actual_starters_1 = startinglineupdata[play.period][1];
                current_lineups.setActualStarters(actual_starters_1);
            }*/
        
        }
        if (!(play.players[0] || play.playEvent.playEventId == 10)) {
            index += 1;
            continue;
        }
        var team_index = teammap[play.players[0]["teamId"]];
        
        if (play.playEvent.playEventId == 10) {
            //create the lineup change
            var lineupChange = LineupChange(pbp, index);
            index += lineupChange.numPlays();
            
            //use it to finish of the segment
            current_segments[team_index].plays.push(play);
            current_segments[team_index].lineupChange = lineupChange;
            current_segments[team_index].finalizeStats(team_index);
            lineupSegments[team_index].push(current_segments[team_index]);
           
            
            current_lineups.updateLineup(team_index, lineupChange);
            current_segments[team_index] = LineupSegment(play, current_lineups.getLineup(team_index));
        }
        else {
            current_segments[team_index].addPlay(play);
        }
        index += 1;
        
    }

    if (current_segments[0].plays.length > 0) {
        current_segments[0].finalizeStats(0);
        lineupSegments[0].push(current_segments[0]);
    
    }
    if (current_segments[1].plays.length > 0) {
        current_segments[1].finalizeStats(1);
        lineupSegments[1].push(current_segments[1]);
    }
    
    return lineupSegments;
}