var debug = require('debug')('liftie:twitter');
var superagent = require('superagent');
var millis = require('../tools/millis');
var limiter = require('../tools/limiter');

var twitterBearerToken = process.env.TWITTER_TOKEN;


// no more than 300 calls per 15 minutes
var limit = limiter(300, 15 * millis.minute);

module.exports = fetch;
module.exports.interval = {
  active: 5 * millis.minute,
  inactive: 6 * millis.hour
};

function trim(tweet) {
  return ['id_str', 'created_at', 'text', 'entities'].reduce(function(r, prop) {
    r[prop] = tweet[prop];
    return r;
  }, {});
}

// API docs: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
function fetch(resort, fn) {
  if (!twitterBearerToken) {
    debug('Configure Twitter bearer token.');
    return process.nextTick(fn);
  }

  if (!resort.twitter) {
    // debug('Twitter handle for %s missing', resort.id);
    return process.nextTick(fn);
  }

  limit(function(err) {
    if (err) {
      debug('Twitter API limit %s', resort.id);
      return fn(err);
    }
    superagent('https://api.twitter.com/1.1/statuses/user_timeline.json')
      .query({
        screen_name: resort.twitter,
        count: 6,
        trim_user: 1,
        exclude_replies: 1,
        include_rts: 0,
        include_entities: 1
      })
      .set('Authorization', 'Bearer ' + twitterBearerToken)
      .end(function(err, res) {
        if (err) {
          return fn(err.status);
        }
        var tweets = res.body.map(trim);
        if (tweets.length > 3) {
          tweets.length = 3;
        }
        debug('Tweets for %s - %j', resort.id, tweets);
        fn(null, {
          user: resort.twitter,
          tweets: tweets
        });
      });
  });
}
@@ -446,22 +446,73 @@
 et) %7B%0A  
-return
+var r = %7B%0A    text: tweet.full_text %7C%7C tweet.text,%0A  %7D;%0A 
  %5B'id_st
@@ -532,16 +532,8 @@
 at',
- 'text',
  'en
@@ -545,14 +545,15 @@
 s'%5D.
-reduce
+forEach
 (fun
@@ -558,19 +558,16 @@
 unction(
-r, 
 prop) %7B%0A
@@ -591,24 +591,28 @@
 et%5Bprop%5D;%0A  
+%7D);%0A
   return r;%0A
@@ -615,18 +615,8 @@
  r;%0A
-  %7D, %7B%7D);%0A
 %7D%0A%0A/
@@ -1314,16 +1314,48 @@
 ities: 1
+,%0A        tweet_mode: 'extended'
 %0A      %7D
@@ -1784,8 +1784,9 @@
 %0A  %7D);%0A%7D
+%0A

add supports for >140 tweets