/* eslint-env node */

var FeedParser = require('feedparser'); // to parse feeds
// var Feed = require('feed'); // to write feeds (but not necessary to require here because we should get a Feed object from app.js -- which seems wrong)
var async = require('async');
// var request = require('request'); // TODO let's abstract this so that we can switch it out (e.g., to fs.readFile )
var fs = require('fs');

exports.feedmerger = function(feedsJson, feedObject, mergedCallback) {
  'use strict';
  // TODO some error handling; checking the arguments etc.

  var getFeed = function(feed, callback) {
    var feedparser = new FeedParser();
    try {
      fs.accessSync(feed);
      var req = fs.createReadStream(feed); // request(feed);
    }
    catch (e){
      console.log('File for ' + feed + ' was not accessible');
      callback();
      return;
    }
    req.on('error', function(error) {
        console.error(error);
    });
    req.on('readable', function() {
      var stream = this;
      stream.pipe(feedparser);
    });
    // req.on('response', function(res) {
    //   var stream = this;
    //   if (res.statusCode !== 200) {
    //     return this.emit('error', new Error('Bad status code'));
    //   }
    //   //    stream.pipe(process.stdout); //works
    //   stream.pipe(feedparser);
    // });
    feedparser.on('error', function(error) {
      console.error(feed + ' as a parsing error' + error);
    });
    feedparser.on('readable', function() {
      // This is where the action is!
      var stream = this;
      //    var meta = this.meta; // **NOTE** the "meta" is always available in the context of the feedparser instance
      var item;
      while ( (item = stream.read())) {
        var itemOptions = {
          date: item.date,
          title: item.title,
          url: item.link,
          guid: item.guid || item.permalink || '',
          description: '',
          author: stream.meta.title
        };
        // console.log(itemOptions);
        feedObject.item(itemOptions);
      }
    });
    feedparser.on('finish', function() {
      callback();
    });
  };

  //  console.log(feedsJson);
  async.eachLimit(feedsJson, 10, getFeed, function(err) {
    if (err) {
      throw err;
    }
    feedObject.items.sort(function(a, b) { //sort by date for creating pages later
      return b.date - a.date;
    });
    //   console.log("feedmerger completed!");
    //     console.log(feedObject.render('atom-1.0'));
    return mergedCallback(feedObject);
  });
};


//    exports.feedmerger = new feedmerger();

@@ -546,16 +546,88 @@
 nts etc.
+%0A  var guids = %5B%5D; // store GUIDs to check against (to avoid duplicates)
 %0A%0A  var 
@@ -1772,24 +1772,156 @@
 .read())) %7B%0A
+        var itemGuid = item.guid %7C%7C item.permalink;%0A        if (guids.indexOf(itemGuid) === -1) %7B%0A          guids.push(itemGuid);%0A  
         var 
@@ -1946,16 +1946,18 @@
         
+  
 date: it
@@ -1965,16 +1965,18 @@
 m.date,%0A
+  
         
@@ -2010,13 +2010,25 @@
     
+  
 url: 
+encodeURI(
 item
@@ -2032,16 +2032,17 @@
 tem.link
+)
 ,%0A      
@@ -2041,24 +2041,26 @@
 ,%0A          
+ 
+ 
 guid: item.g
@@ -2061,39 +2061,22 @@
 item
-.g
+G
 uid %7C%7C
- item.permalink %7C%7C
  '',%0A
+  
     
@@ -2094,24 +2094,26 @@
 iption: '',%0A
+  
           au
@@ -2144,19 +2144,23 @@
         
+  
 %7D;%0A
+  
         
@@ -2192,24 +2192,26 @@
 s);%0A        
+  
 feedObject.i
@@ -2224,24 +2224,34 @@
 emOptions);%0A
+        %7D%0A
       %7D%0A    

implement check for duplicate GUIDs