var express = require('express');
var router = express.Router();
var passport = require('passport');
var constants = require('./../config/constants.js');
var request = require('request');
var twit = require('twit');

function isAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/');
}

router.get('/', function(req, res) {
  if (req.isAuthenticated()) {
    return res.redirect('/dashboard');
  }
  res.render('index');
});

router.get('/login', passport.authenticate('twitter'));

router.get(constants.Twitter.CALLBACK,
    passport.authenticate('twitter', {
      successRedirect: '/dashboard',
      failureRedirect: '/'
    })
);

router.get('/dashboard', isAuthenticated, function(req, res) {
  res.render('dashboard');
});

router.post('/tweet', isAuthenticated, function(req, res) {
  var API_URL = 'https://upload.twitter.com/1.1/media/upload.json';

  var image = req.body.image.replace(/^data.*base64,/, '');

  // First we post to media/upload.json
  request.post(API_URL, {
    oauth: {
      consumer_key: constants.Twitter.KEY,
      consumer_secret: constants.Twitter.SECRET,
      token: req.user.access_token,
      token_secret: req.user.access_token_secret
    },
    form: {
      media: image
    },
    json: true
  }, function (err, response, body) {
    console.log(body);
    // body = JSON.parse(body);
    var T = new twit({
      consumer_key: constants.Twitter.KEY,
      consumer_secret: constants.Twitter.SECRET,
      access_token: req.user.access_token,
      access_token_secret: req.user.access_token_secret
    });

    T.post('statuses/update', { status: 'Testing', media_ids:  body.media_id_string}, function(err, data, response) {
      // data = JSON.parse(data);
      console.log(data.id_str);
    });
  });
});

module.exports = router;

@@ -1346,40 +1346,8 @@
 y);%0A
-    // body = JSON.parse(body);%0A
     
@@ -1596,16 +1596,22 @@
 date', %7B
+%0A     
  status:
@@ -1621,16 +1621,22 @@
 esting',
+%0A     
  media_i
@@ -1638,17 +1638,16 @@
 dia_ids:
- 
  body.me
@@ -1698,42 +1698,8 @@
 ) %7B%0A
-      // data = JSON.parse(data);%0A
     

clean up some console.logs