/* DBConnector
 * Connecting to postgres and querying the database
 */
 
var proto = DBConnector.prototype;

function DBConnector(environment) {
    this._pgp = require('pg-promise')();
    this._connections = {
        development:  {
            host: 'localhost', // server name or IP address; 
            port: 5432,
            database: 'development',//'development',
            user: 'postgres',
            password: 'steph43'
        },
        production: process.env.DATABASE_URL
    }
    
    this._db = this._pgp(this._connections[environment]);
}

proto.indexBy = function(array, property) {
    var results = {};
    (array||[]).forEach(function(object) {
        results[object[property]] = object;
    });
    return results;
};

proto.getPlayerData = function(player_names, callback) {
    this._db.any("SELECT * FROM player_data WHERE first_last in ($1^);", this._pgp.as.csv(player_names)).then((function (data) {
        callback(null, this.indexBy(data, 'first_last'));
    }).bind(this))
    .catch(function (error) {
        console.log("Error: " + error)
        callback('error', error);
    });
}

proto.getLineupDataForTeam = function(team_name, callback) {
    // create map of key: lineup data
    var query = "SELECT a.* FROM lineup_traditional_stats a JOIN team_overview b ON a.team_id = b.team_id WHERE b.team_name = $1";
    this._db.any(query, team_name).then((function (data) {
        var lineupdata = this.indexBy(data, 'group_name');
        var data = {team : team_name, data : lineupdata};
        callback(null, data);
    }).bind(this))
    .catch(function (error) {
        console.log("Error: " + error);
        callback('error', error);
    });
}

// takes in player object
proto.getLineupKey = function(players) {
    var formatted_player_arr = [];
    for (var key in players) {
        formatted_player_arr.push([players[key].lastName, players[key].firstName].join(','));
    }
    formatted_player_arr = formatted_player_arr.sort();
    return formatted_player_arr.join(' - ');
}

module.exports = DBConnector;