var rss = require('rss');
var Slack = require('slack-node');

apiToken = process.env.SLACK_API_KEY;
slack = new Slack(apiToken);

var feed = new rss({
  title: "Assembled Brands",
  description: "The links that have been posted to the #interesting_read on Slack",
  site_url: 'https://assembledbrands.com',
  ttl: '30',
});

slack.api('channels.list', function(err, response) {
  for(var c=0; c< response.channels.length; c++) {
    var channel = response.channels[c];

    if(channel.name == 'interesting_read') {
      slack.api('channels.history', {'channel':channel.id,'count':process.env.HISTORY_LENGTH} ,function(err, response){
        for(var i = 0; i < response.messages.length; i++) {
          if(response.messages[i].attachments && response.messages[i].subtype != "bot_message") {
            for(var j = 0; j < response.messages[i].attachments.length; j++) {
              if(response.messages[i].attachments[j].title) {
                var link = response.messages[i].attachments[j];

                var t = new Date(response.messages[i].ts * 1000);

                feed.item({
                  title: link.title,
                  description: link.text,
                  url: link.title_link,
                  date: t,
                  custom_elements: [{
                    'media:thumbnail': {
                      _attr: {
                        'xmlns:media': "http://search.yahoo.com/mrss/",
                        url: link.image_url
                      }
                    }
                  }]
                });
              }
            }
          }
        }
    });
    }
  }
});

module.exports = feed;
