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,
  getResource: getResource,
  render: render,
  replaceMarkdown: replaceMarkdown
};

function getResource(url) {
  var i = url.lastIndexOf('/');
  var path = url.slice(1, i);
  if(path == blog.path.articlesPath) {
    return {type: 'article', key: url.slice(i+1).replace(/\.html/, '')};
  } else if(path == blog.path.pagesPath) {
    return {type: 'page', key: url.slice(i+1).replace(/\.html/, '')};
  } else if(path == '' || blog.tags[path] != undefined) {
    var tag = path.length > 0 ? path : undefined;
    return {type: 'list', tag: tag, all: url.slice(i+1) == 'all.html'};
  } else {
    return {type: 'unknown'};
  }
}

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

function replaceMarkdown() {
  var div = document.getElementById('contents');
  if(div.children[0] && div.children[0].tagName.toLowerCase() == 'article') {
    var resourceType = getResource(window.location.pathname).type;
    convertContent(resourceType, 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(resourceType, article, comments) {
  var header = article.getElementsByTagName('header')[0];
  if(resourceType == 'article') {
    header.appendChild(Metadata.get(article.id));
  }
  var text = article.getElementsByTagName('pre')[0];
  if(text != undefined) {
    article.replaceChild(getDiv(text.innerText), text);
    if(resourceType == '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 commentsSection(resource, limit) {
  if(resource.type != 'article' || limit != undefined) {
    return [];
  } else {
    return Metadata.getComments(resource.key);
  }
}

function render(resource, markdown, limit) {
  var url = resourceUrl(resource, limit);
  var content = blog[resource.type + 's'][resource.key];
  var lines = markdown.split(/\n/).slice(content.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: content.title})
      ])].concat(resource.type == 'article' ? Metadata.get(resource.key) : [])
    ),
    div
  ].concat(commentsSection(resource, limit)));
}

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

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

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

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