'use strict';

const jsdom = require('jsdom'),
      jquery = require('jquery'),
      url = require('url');

function relative(uri) {
  return !url.parse(uri || '').host;
}

function fullUrl(uri, baseUrl) {
  return (uri && relative(uri)) ? url.resolve(baseUrl, uri) : uri;
}

function removeIframes($doc) {
  $doc.find('iframe').remove();
}

function removeScriptTags($doc) {
  $doc.find('script').remove();
}

function removeStylesheets($doc) {
  $doc.find('link[rel=stylesheet]').remove();
  $doc.find('style').remove();
}

function fixImages($doc, $, baseUrl) {
  $doc.find('img')
    .filter((_, el) => relative($(el).attr('src')))
    .each((_, el) => {
      const $el = $(el),
            src = $el.attr('src');
      $el.attr('src', fullUrl(src, baseUrl));
    });
}

function fixRelativeUrls($doc, $, baseUrl) {
  $doc.find('a').each((_, el) => {
    const link = $(el),
          href = link.attr('href');
    link.attr('href', fullUrl(href, baseUrl));
  });
}

function removeShareLinks($doc) {
  $doc.find('div.feedflare').remove();
}

function removeEmptyLinks($doc, $) {
  $doc.find('a')
    .filter((_, el) => $(el).html().trim().length === 0)
    .remove();
}

module.exports = (html, postUrl, cb) => {
  const opts = {
    FetchExternalResources: false,
    ProcessExternalResources: false,
    MutationEvents: false,
    QuerySelector: false
  };

  if (!postUrl) {
    return cb(new Error(`Invalid post url ${postUrl}`));
  }

  function process(err, window) {
    if (err) { return cb(err, html); }

    const $ = jquery(window),
          $doc = $(window.document);

    removeIframes($doc, $, postUrl);
    removeScriptTags($doc, $, postUrl);
    removeStylesheets($doc, $, postUrl);
    fixImages($doc, $, postUrl);
    fixRelativeUrls($doc, $, postUrl);
    removeShareLinks($doc, $, postUrl);
    removeEmptyLinks($doc, $, postUrl);

    if (window.document.body) {
      cb(null, window.document.body.innerHTML);
    } else {
      cb(null, window.document.innerHTML);
    }
  }

  try {
    jsdom.env({
      features: opts,
      html,
      done: process,
      url: postUrl
    });
  } catch (jsdomErr) {
    cb(jsdomErr, html);
  }
};


@@ -531,28 +531,37 @@
 nction fixIm
-ages
+gUrlAttribute
 ($doc, $, ba
@@ -557,32 +557,38 @@
 $doc, $, baseUrl
+, name
 ) %7B%0A  $doc.find(
@@ -637,21 +637,20 @@
 l).attr(
-'src'
+name
 )))%0A    
@@ -705,19 +705,20 @@
         
-src
+attr
  = $el.a
@@ -721,21 +721,20 @@
 el.attr(
-'src'
+name
 );%0A     
@@ -747,13 +747,12 @@
 ttr(
-'src'
+name
 , fu
@@ -761,29 +761,169 @@
 Url(
-src, baseUrl));%0A    %7D
+attr, baseUrl));%0A    %7D);%0A%7D%0A%0Afunction fixImages($doc, $, baseUrl) %7B%0A  fixImgUrlAttribute($doc, $, baseUrl, 'src');%0A  fixImgUrlAttribute($doc, $, baseUrl, 'srcset'
 );%0A%7D

Set full urls for post images