var fs = require('fs');
// var async = require('async');
var _ = require('underscore');
var pg = require('pg');
  pg.defaults.database = 'intersect_test';
  pg.defaults.host = 'localhost';
  pg.defaults.user = 'mrbuttons';
  pg.defaults.password = 'mrbuttons';

// {
//     id: '12345',
//     lon: "-40.123",
//     lat: "12.456",
//     street1: "my street",
//     street2: "your street"
// }


//input: [{}]
//output: [{}]
function parse_osm_json(osm) {
    return _.chain(osm)
            .map(function(point){
                 var streets = reduceWays(point.ways);
                    if (streets) {
                         return _.extend({
                                id: point.$.id,
                                lon: point.$.lon,
                                lat: point.$.lat,
                        }, streets)
                    }})
            .compact()
            .value()
}

// returns streets only if there are 2 unique streets
// outputs: {} or false
function reduceWays(ways) {
    if (ways.length === 2) {
        if (get_name(ways[0].tag) && get_name(ways[1].tag)) {
            return {
                street1: get_name(ways[0].tag),
                street2: get_name(ways[1].tag)
            }
        } else {
            return false;
        }
    } else if (ways.length === 3) {
        return handle3ways(ways);
    } else {
        return false;
        console.log('more than 3 ways')
    }

}

// [] -> {} or false
function handle3ways(ways) {
    // imagine there are three names: A B C
    // three comparisions: A = B, A = C, B = C,
    var names = _.map(ways, function(way){
        return get_name(way.tag);
    })
    if (names[0] === names[1] && names[0] === names[2]) { 
        return false; 
    }
    // remove C from the list
    var c = names.pop();
    // checks A = C, B = C
    if (c === names[0] || c === names[1]) {
        return {
            street1: names[0],
            street2: names[1]
        }
    // checks A = B    
    } else if (names[0] === names[1]) {
        return {
            street1: names[0],
            street2: c
        }
    } else {
        console.log('a intersection of three streets!');
        return {
            street1: names[0],
            street2: c
        }
    }
}

// from array of tags returns the value of the 'name' tag or FALSE if it doesn't exist
//ouput: str or FALSE
function get_name(tags) {
    var name = _.find(tags, function(tag){
        return (tag.$.k === 'name')
    })
    return (_.isUndefined(name)) ? false : name.$.v;
}
// input: pg (ref to module), str (sql statement), callback
function do_query(pg, sql, whenDone) {
  pg.connect(function(err, client, done){
    if (err) {
        return console.error('error fetching client from pool', err)
    }
    client.query(sql, function(err, result){
        if (err) {
          console.error('error executing query', err);
        }
        done();
        whenDone(result);
    });
  });
}


module.exports = {
    do_query: do_query,
    get_name: get_name,
    reduceWays: reduceWays,
    handle3ways: handle3ways,
    parse_osm_json: parse_osm_json

}

// does SQL query; 