var express = require('express'), path = require('path'), http = require('http'),
    fx = require('./lib/fx'), btc = require('./lib/btc'), train = require('./lib/train'),
    password = require('./lib/password') , clean = require('./lib/clean'), events = require('./lib/events'),
    today = require('./lib/today'),
    morgan = require('morgan'), cookieParser = require('cookie-parser'),session = require('express-session')
 methodoverride = require('method-override'), bodyparser = require('body-parser'), errorhandler = require('errorhandler');

var jsonfile = require('jsonfile');

    //train = require('lib/train')
/* ,submit = require('./routes/mongo/submit') */
    ;

var fs = require('fs');
var config = require('./config/config.json');
var Fitbit = require('fitbit-oauth2');

var polys = require('./lib/poly.js');

var logger = require('log4js').getLogger();
var app = express();
GLOBAL.lastcheck = 0;
var btcCache = {}, fxCache = {} , trainCache = {};

//app.configure(function () {
    app.set('port', process.env.PORT || 9000);
    app.set('view engine', 'ejs');
    app.use(morgan('dev'));
    app.use(cookieParser('your secret here'));
app.use(session({
    secret: '1234567890QWERTY', resave: false,
    saveUninitialized: false
}));
    /* 'default', 'short', 'tiny', 'dev' */
    app.use(methodoverride());

app.use(bodyparser.urlencoded({extended: false}));

// parse application/json
app.use(bodyparser.json());

    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(errorhandler({dumpExceptions: true, showStack: true}));

app.use('/btc', btc.doBTC);

    app.use('/fx', fx.doFx);

    app.use('/dbeglq', train.dbe_glq);
    app.use('/glqdbe', train.glq_dbe);
    app.use('/gettrains', train.getTrainTimes);
    app.use('/getnexttraintimes', train.getNextTrainTimes);
    app.use('/getroute', train.getRoute);

    app.use('/generate', password.generate);

    app.use('/cleanit', clean.cleanit);



    app.use('/events', events.getEvents);
    app.get('/cinema/:id', events.getCinema);

    app.get('/today', today.getToday);
    app.get('/today/data', today.getData);

    app.route('/clock')
        .get(today.getClock);

app.route('/poly').get(polys);


    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();
            });
        });
    });

    app.get('/slack', function (req, res) {
        res.render('pages/slack');
    });

    app.get('/temp', function (req, res) {
        res.render('pages/temp');
    });



var tfile = 'fb-token.json';


// Instanciate a fitbit client.  See example config below.
//


var fitbit = new Fitbit( config.fitbit);

// In a browser, http://localhost:4000/fitbit to authorize a user for the first time.
//
app.get('/fitbit', function (req, res) {
    res.redirect( fitbit.authorizeURL() );
});

// Callback service parsing the authorization token and asking for the access token.  This
// endpoint is refered to in config.fitbit.authorization_uri.redirect_uri.  See example
// config below.
//
app.get('/fitbit_auth_callback', function (req, res, next) {
    var code = req.query.code;
    fitbit.fetchToken( code, function( err, token ) {
        if ( err ) {
          return next( err );
        }

        // persist the token
        jsonfile.writeFile( tfile, token, function( err ) {
            if ( err ) {
              return next( err );
            }
            res.redirect( '/fb-profile' );
        });
    });
});

jsonfile.readFile('./fb-token.json', function(err, obj) {
          if (err) {
                logger.error(err);

          }
          else {
              fitbit.setToken(obj);

          }
        });


//});

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