/* global chrome */


/* This is the user file part of reader mode, it's injected after the
   browserjs part of reader mode and does the real injecetion
   (browserjs only does detection at an earlier stage so that we don't
   need to wait for the page to load to update the indicator status of
   the readability of the page */

const FEATURE_HIDE_PAGE = true; /* Hide page on load for better transition while navigating */

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

// TODO: not working after delaying injection in the browserjs part of reader view
if (FEATURE_HIDE_PAGE && canSetStyle()) {
  document.documentElement.style.display = 'none';
}

const DEBUG_READABILITY = false;

const readabilityCss = `
html {
  margin: 0;
  padding: 0;
}
body {
  color: #111111;
  background-color: #f6f6f6;
  font-family: sans-serif;
  font-size: 1.3em;
  font-style: normal;
  font-weight: 400;
  line-height: 1.5;
  margin: 0 auto;
  padding: 40px 10px 80px;
  text-orientation: upright;
  transition:
    color 200ms cubic-bezier(0.4, 0, 1, 1),
    background-color 200ms cubic-bezier(0.4, 0, 1, 1);
}
body.vertical {
  margin: 40px auto 0;
  padding: 40px 60px 0;
  max-height: calc(100vh - 120px);
}
.entry-content * {
  max-width: 100%;
  white-space: normal;
  line-height: inherit;
  vertical-align: baseline;
  background: transparent;
}
.entry-content p {
  margin: 1.5em 0;
}
body.vertical .entry-content p {
  margin: 0 1.5em;
}
h1 {
  font-size: 1.8em;
  line-height: 1.35;
}
h1, h2, h3, h4, h5, h6, b {
  font-weight: 700;
}
hr {
  border-style: solid;
  border-width: 0 0 0.5px 0.5px;
}
.byline {
  font-style: italic;
}
.entry-content img {
  max-width: 100%;
  height: auto;
}
body.vertical .entry-content img {
  max-height: 100%;
  width: auto;
}
.entry-content code {
  font-weight: 500;
}
.entry-content pre {
  font-weight: 300;
  background-color: rgba(128, 128, 128, 0.05);
  border: 1px solid rgba(128, 128, 128, 0.1);
  white-space: pre-wrap;
  padding: 0.5em;
  margin: 1.5em 0;
}
.entry-content code, .entry-content pre {
  text-align: left;
  max-width: 100%;
  writing-mode: horizontal-tb;
  overflow: auto;
  white-space: pre-wrap;
}
body.vertical .entry-content pre {
  margin: 0 1.5em;
  max-width: 80%;
  max-height: 100%;
}
iframe, textarea, input {
  display: none;
}
`;

function __vivaldiGetHTML(article) {
  const content = window.DOMPurify.sanitize(article.content);
  return `<!DOCTYPE html>
<html dir="${article.dir}"><head>
<title>${article.title}</title>
<style>${readabilityCss}</style>
</head><body>
<h1>${article.title}</h1>`+
(article.byline ? `<p class="byline">${article.byline}</p>` : '') +
`<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;
}

let _numTriesLeft = 5;
function onLoad() {
  if (!window['Readability'] && _numTriesLeft-- > -1) {
    setTimeout(onLoad, 500);
  }
  try {
    if (!window['Readability']) {
      return;
    }

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

    const isProbablyReaderable = window.Readerable.isProbablyReaderable(document);

    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) {
      // VB-22288 Cancel unload events
      document.beforeunload = () => {};
      document.unload = () => {};
      const reader = document.implementation.createHTMLDocument(document.title);
      reader.documentElement.innerHTML = __vivaldiGetHTML(article);
      document.replaceChild(reader.documentElement, document.documentElement);
      if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
        chrome.runtime.sendMessage({type: 'SET_RM_STYLE'});
      }
    } 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);
}
