var outputFile = 'news', RssBraider = require('rss-braider'), fs = require('fs'), ejs = require(
  'ejs'), read = require('fs').readFileSync, join = require('path').join, str = read(
  join(__dirname, '/templates/rss.ejs'),
  'utf8'), feeds = {};
var jsonfile = require('jsonfile');
var argv = require('yargs').argv;


var log4js = require('log4js');
var logger = log4js.getLogger();

var feedFileName = argv.feeds + '.json';

logger.debug(feedFileName);

feeds.simple_test_feed = {} ;

var braider_options = {
  feeds: feeds,
  indent: "    ",
  date_sort_order: "desc", // Newest first
  log_level: "warn",
  dedupe_fields: ['link', 'guid'],
  plugins_directories: [__dirname + "/plugins/"]
};
var rss_braider = RssBraider.createClient(braider_options);

// Override logging level (debug, info, warn, err, off)
//rss_braider.logger.level('off');

jsonfile.readFile(feedFileName, function (err, obj) {

  if (err) {
    logger.error(err);
    return -1;
  }

  feeds.simple_test_feed = obj;

  rss_braider.processFeed('simple_test_feed', 'json', function(err, data) {
    console.log('A');
    if (err) {
      logger.error(err);
      return err;
    }

    console.log('B');

    var j = JSON.parse(data);

    console.log('C');
    var ejsOutput = ejs.compile(str)(j);

    console.log('D');
    fs.writeFile(__dirname + "/dist/" + outputFile + ".html",
      ejsOutput,
      function(err) {

        if (err) {
          logger.error(err);
          return console.error(err);
        }

        console.log("The file was saved!");
      });

    fs.writeFile(__dirname + "/dist/" + outputFile + ".json",
      data,
      function(err) {
        if (err) {
          logger.error(err);
          return console.error(err);
        }

        console.log("The file was saved!");
      });
  });


});




