import blog from Hablo.Config;
import Metadata;
import Remarkable;
import Template;
import * as Dom from UnitJS.Dom;
import {defined} from UnitJS.Fun;

return {
  articlesList: articlesList,
  render: render,
  replaceMarkdown: replaceMarkdown
};

function replaceMarkdown() {
  var div = document.getElementById('contents');
  if(div.children[0] && div.children[0].tagName.toLowerCase() == 'article') {
    var contentType = window.location.pathname.slice(1).replace(/\/.*/, '');
    convertContent(contentType, div.children[0], true);
  } else {
    var articles = div.getElementsByClassName('articles')[0];
    if(articles != undefined) {
      for(var i = 0; i < articles.children.length; i++) {
        convertContent('article', articles.children[i]);
      }
    } else {
      console.log('No articles found for this page');
    }
  }
}

function convertContent(contentType, article, comments) {
  var header = article.getElementsByTagName('header')[0];
  if(contentType == 'article') {
    header.appendChild(Metadata.get(article.id));
  }
  var text = article.getElementsByTagName('pre')[0];
  if(text != undefined) {
    article.replaceChild(getDiv(text.innerText), text);
    if(contentType == 'article' && comments) {
      Metadata.getComments(article.id)
        .forEach(article.appendChild.bind(article));
    }
  } else {
    console.log('No content found for this article');
  }
}

function getDiv(markdown) {
  var d= Dom.make('div', {
    innerHTML: Remarkable.md.render(markdown)
  });
  var scripts = d.getElementsByTagName('script');
  for(var i = 0; i < scripts.length; i++) {
    var run = Dom.make('script',
      {type: 'text/javascript', src: scripts[i].src, textContent: scripts[i].textContent}
    );
    scripts[i].parentNode.replaceChild(run, scripts[i]);
  }
  return d;
}

function contentUrl(contentType, key, limit) {
  var directory = blog.path[contentType + 'sPath'];
  var extension = limit != undefined ? '.html' : '.md';
  return ["", directory, key + extension].join('/');
}

function commentsSection(contentType, key, limit) {
  if(contentType != 'article' || limit != undefined) {
    return [];
  } else {
    return Metadata.getComments(key);
  }
}

function render(contentType, key, markdown, limit) {
  var url = contentUrl(contentType, key, limit);
  var resource = blog[contentType + 's'][key];
  var lines = markdown.split(/\n/).slice(resource.bodyOffset);
  var div = getDiv(lines.slice(0, limit).join('\n'));
  return Dom.make('article', {}, [
    Dom.make('header', {}, [
      Dom.make('h1', {}, [
        Dom.make('a', {href: url, innerText: resource.title})
      ])].concat(contentType == 'article' ? Metadata.get(key) : [])
    ),
    div
  ].concat(commentsSection(contentType, key, limit)));
}

function pageTitle(tag, all) {
  return Template.render(all ? 'allPage' : 'latestPage', {tag: tag});
}

function otherUrl(tag, all) {
  var path = [tag, all ? '' : 'all.html'];
  return '/' + path.filter(defined).join('/');
}

function articlesList(tag, all) {
  return function(articlePreviews) {
    return [
      Dom.make('h2', {innerText: pageTitle(tag, all)}),
			Dom.make('ul', {}, articlesListLinks(tag, all)),
      Dom.make('div', {class: 'articles'}, articlePreviews.filter(defined))
    ];
  };
}

function articlesListLinks(tag, all) {
  var links = [
    Dom.make('a', {
      innerText: all ? blog.wording.latestLink : blog.wording.allLink,
      href: otherUrl(tag, all),
      class: 'other'
    })
  ];
  if(blog.hasRSS) {
    links.unshift(Dom.make('a', {
      innerText: blog.wording.rssLink,
      href: 'rss.xml',
      class: 'RSS',
      title: Template.render('rssTitle', {tag: tag})
    }));
  }
  return links.map(function(e) {return Dom.make('li', {}, [e]);});
}