var express = require('express'), path = require('path'), http = require('http')
/* ,submit = require('./routes/mongo/submit') */
    ;
var app = express();
var lastcheck = 0;
var btcCache = {}, fxCache = {} , trainCache = {};

app.configure(function () {
    app.set('port', process.env.PORT || 9000);
    app.use(express.logger('dev'));
    app.use(express.cookieParser());
    app.use(express.session({secret: '1234567890QWERTY'}));
    /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.methodOverride());

    app.use(express.bodyParser());

    app.use(function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
    });
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'app')));
    app.use(express.errorHandler({dumpExceptions: true, showStack: true}));

    app.use('/btc', function (req, res) {
        console.log('Bitcoin request');
        function btcQuery(callback, r) {
            var req = r;
            var options = {
                host: 'api.coindesk.com',
                //  port: 80,
                path: '/v1/bpi/currentprice.json',
                // method: 'GET',
                headers: {
                    /*   'Content-Type': 'application/json',
                     'Content-Length': Buffer.byteLength(data)*/

                }
            };

            http.request(options).on('response', function (response) {
                var data = '';
                response.on("data", function (chunk) {
                    data += chunk;
                });
                response.on('end', function () {
                    callback(JSON.parse(data), r);
                });
            }).end();
        }

        var now = new Date();
        if (now - lastcheck > (59000 )) {
            btcQuery(function (a, b) {
                console.log(a);
                btcCache = a;
                lastcheck = now;
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(btcCache));
            }, res)
        }
        else {
            console.log("Using cache");
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(btcCache));
        }
    });

    app.use('/fx', function (req, res) {
        console.log('FX request');
        function fxQuery(callback, r) {
            var req = r;
            var options = {
                host: 'openexchangerates.org',
                //  port: 80,
                path: '/api/latest.json?app_id=0eb932cee3bc40259f824d4b4c96c7d2',
                // method: 'GET',
                headers: {
                    /*   'Content-Type': 'application/json',
                     'Content-Length': Buffer.byteLength(data)*/

                }
            };

            http.request(options).on('response', function (response) {
                var data = '';
                response.on("data", function (chunk) {
                    data += chunk;
                });
                response.on('end', function () {
                    callback(JSON.parse(data), r);
                });
            }).end();
        }

        var now = new Date();
        if (now - lastcheck > (60000 * 14)) {
            fxQuery(function (a, b) {
                console.log(a);
                fxCache = a;
                lastcheck = now;
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(fxCache));
            }, res);
        }
        else {
            console.log("Using cache");
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(fxCache));
        }
    });

    app.use('/lot', function (req, res) {
        var pg = require('pg');

        var conString = "postgres://pguser:1V3D4m526i@localhost/silver";
        console.log(conString);


        var client = new pg.Client(conString);
        var q = 'select * from lot order by d desc';
        client.connect(function(err) {
            if(err) {
                return console.error('could not connect to postgres', err);
            }
            client.query(q, function(err, result) {
                if(err) {
                    return console.error('error running query', err);
                }
                console.log(result.rows[0].theTime);
                //output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
                client.end();
            });
        });
    });
});

/**
 * create the server
 */
http.createServer(app).listen(app.get('port'), function () {
    console.log("Express server listening on port " + app.get('port'));
});
