var env = process.env,
    https = require('https'),
    gzip = require('zlib'),
    Twitter = require('ntwitter'),
    
twitter = new Twitter({
    consumer_key: env.TWITTER_CONSUMER_KEY,
    consumer_secret: env.TWITTER_CONSUMER_SECRET,
    access_token_key: env.TWITTER_TOKEN_KEY,
    access_token_secret: env.TWITTER_TOKEN_SECRET
});

function defErrorHandler(err) {
    if (err) {
        console.error(err);
    }
}

function sendToTwitter(question) {
    var tweet = question.title;
    // Twitter shortens URLs up to 20 characters
    // ' #yui' is 5 characters long
    // So we take 30 characters of title just in case
    if (tweet.length > 110) {
        tweet = tweet.substr(0, 107) + '...';
    }
    console.log('Question: ' + tweet);
    tweet += ' http://stackoverflow.com/questions/' + question.question_id + ' #YUI';
    twitter.updateStatus(tweet, defErrorHandler);
}

exports.check = function (mins) {
    var lastRunTimeInSeconds = Math.floor(new Date(new Date().toUTCString()).getTime() / 1000) - 60 * mins,
        apiPath = '/2.0/questions?fromdate=' + lastRunTimeInSeconds +
                  '&order=desc&sort=creation&tagged=yui&site=stackoverflow&key=' +
                  env.SO_KEY;
    console.log('Checking Stack Overflow: http://api.stackexchange.com' + apiPath);
    https.get({ host: 'api.stackexchange.com', path: apiPath }, function (res) {
        var result = '';
        res
            .pipe(gzip.createGunzip())
            .on('data', function (chunk) {
                result += chunk;
            })
            .on('end', function () {
                result = JSON.parse(result);
                if (result.error_id) {
                    defErrorHandler(result);
                } else {
                    console.log('Publishing ' + result.items.length + ' questions...');
                    result.items.forEach(sendToTwitter);
                }
            });
    }).on('error', defErrorHandler);
};
exports.say = function (msg) {
    if (msg.length > 140) {
        console.error('Message longer than 140 characters');
    } else {
        twitter.updateStatus(msg, defErrorHandler);
    }
};
@@ -557,45 +557,8 @@
 rs%0D%0A
-    // ' #yui' is 5 characters long%0D%0A
     
@@ -575,10 +575,10 @@
 ake 
-30
+25
  cha
@@ -633,17 +633,17 @@
 gth %3E 11
-0
+5
 ) %7B%0D%0A   
@@ -676,10 +676,10 @@
 0, 1
-07
+12
 ) + 
@@ -811,18 +811,8 @@
 n_id
- + ' #YUI'
 ;%0D%0A 

remove #yui hashtag