/* global Readability */
const FEATURE_HIDE_PAGE = true;

function canSetStyle() {
  return document && document.documentElement && document.documentElement.style;
}

if (FEATURE_HIDE_PAGE && canSetStyle()) {
  document.documentElement.style.display = 'none';
}

const DEBUG_READABILITY = false;

const readabilityCss = `
.entry-content p {
  margin: 1.5em 0 1.5em 0;
}

h1 {
  font-size: 2em;
  line-height: 1.2;
}

h1, h2, h3, h4, h5, h6, b {
  font-weight: 700;
}

body {
  max-width: 700px;
  font-family: Helvetica, Arial, sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 1.3em;
  line-height: 1.5;
  margin: 0 auto;
  background-color: #f8f8f8;
}

img {
  max-width: 680px;
}

code, pre {
  background-color: #fff;
  padding: 0.3em 0.4em;
  text-align: left;
  font-weight: 300;
}

iframe, textarea, input {
  display: none;
}
`;

function __vivaldiGetHTML(article) {
  const content = window.DOMPurify.sanitize(article.content);
  return `<html><style>${readabilityCss}</style><body><h1>${article.title}</h1>
<hr />
<article class="entry-content">${content}</article></body></html>`;
}

function ready() {
  if (typeof document !== 'undefined' &&
      ['complete', 'loaded', 'interactive'].indexOf(document.readyState) > -1) {
    return true;
  }
  return false;
}

var _numTriesLeft = 5;
function onLoad() {
  if (! window['Readability'] && _numTriesLeft-- > -1) {
    setTimeout(onLoad, 200);
  }
  try {
    const loc = document.location;

    const uri = {
      spec: loc.href,
      host: loc.host,
      prePath: loc.protocol + '//' + loc.host,
      scheme: loc.protocol.substr(0, loc.protocol.indexOf(':')),
      pathBase: loc.protocol + '//' +
                loc.host + loc.pathname.substr(0, loc.pathname.lastIndexOf('/') + 1)
    };

    // TODO: should probably reuse this object when enabling, instead
    // of running it again via the user script
    const readability = new Readability(uri, document.cloneNode(true),
                                        DEBUG_READABILITY && {debug: true});

    const isProbablyReaderable = readability.isProbablyReaderable();

    let article;

    if (isProbablyReaderable) {
      article = readability.parse();
    } else {
      console.log('[readability] Probably not readable');
    }

    if (DEBUG_READABILITY) {
      console.log('isReadable?', isProbablyReaderable, 'article:', article);
    }

    if (article) {
      const readableDocument = document
        .implementation.createHTMLDocument('Readability');

      readableDocument.documentElement.innerHTML = __vivaldiGetHTML(article);

      document.replaceChild(
        readableDocument.documentElement, document.documentElement);
    } else {
      console.log('[readability] Nothing to show');
    }
  } finally {
    // The page is rendered with display: none, so need to ensure this
    // is always called
    if (FEATURE_HIDE_PAGE && canSetStyle()) {
      document.documentElement.style.display = 'block';
    }
  }
}

if (ready()) {
  onLoad();
} else {
  window.addEventListener('DOMContentLoaded', onLoad, false);
}
