const FeedMe = require('feedme');
const fecha = require('fecha');
const http = require('http');

const logger = require('log4js').getLogger('euronews');

module.exports = {
  'getEuroNews': doGetEuroNews,
  'render': render

};

class Template {
  constructor(item) {
    // "pubdate": "Tue, 06 Feb 2018 17:05:00 +0100",
    const pubdateSrc = fecha.parse(item.pubdate, 'ddd, DD MMM YYYY HH:mm:SS ZZ');
    const pubdate = fecha.format(pubdateSrc, 'dddd MMMM Do, YYYY');
    const description = item.description.replace(/(<script(\s|\S)*?<\/script>)|(<style(\s|\S)*?<\/style>)|(<!--(\s|\S)*?-->)|(<\/?(\s|\S)*?>)/g, '');
    this.data = `<article>
<header>
<a href="${item.guid.text}">${item.title}</a>
<time class="published">${pubdate}</time>
</header>
<p class="description">${description}</p>
</article>`;
  }

  toString() {
    return this.data;
  }
}

function doGetEuroNews() {
  return new Promise((resolve, reject) => {
    logger.info('Retrieving Euronews Headlines..');

    http.get('http://feeds.feedburner.com/euronews/en/news/', (res) => {
      const { statusCode } = res;
      const contentType = res.headers['content-type'];

      let error;

      if (statusCode !== 200)
        error = new Error('Request Failed.\n' +
                            `Status Code: ${statusCode}`);
      else if (!/^text\/xml/.test(contentType))
        error = new Error('Invalid content-type.\n' +
                            `Expected text/xml but received ${contentType}`);

      if (error) {
        logger.error(error.message);
        // consume response data to free up memory
        res.resume();

        return reject(error);
      }

      const parser = new FeedMe(true);
      res.pipe(parser);
      parser.on('end', () => {
        return resolve(parser.done());
      });
    });
  });
}

function render(data) {
  logger.debug('Rendering euronews');
  // logger.debug(JSON.stringify(data));

  const html = [];
  const items = data.slice(0, 10);
  for (const item of items)
    html.push(new Template(item).toString());

  return(html.join(''));
}
