var assert = require('assert');

module.exports = function formatText(text, options) {
  assert(text.shift() == 'text');

  var result = [];
  text.forEach(function(block) {
    result.push(formatBlock(block));
  });

  var output = result.join('\n\n') + '\n';
  if (options.standalone)
    output = header + output + footer;
  return output;
};

function formatBlock(block) {
  var type = block.shift();
  var attr = block.shift();

  var spans = [];
  block.forEach(function(span) {
    spans.push(formatSpan(span));
  });
  var text = spans.join('');

  switch (type) {
    case 'heading': return '<h1>' + text + '</h1>';
    default: return '<p>' + text + '</p>';
  }
}

function formatSpan(span) {
  var type = span.shift();
  var text = span.shift();
  assert(span.length === 0);

  switch (type) {
    case 'emph': return '<em>' + escape(text) + '</em>';
    case 'strong': return '<strong>' + escape(text) + '</strong>';
    case 'code': return '<code>' + escape(text) + '</code>';
    case 'url': return '<a href="' + text + '">' + escape(text) + '</a>';
    default: return escape(text);
  }
}

function escape(str) {
  return str.
    replace(/&/g,'&amp;').
    replace(/</g,'&lt;').
    replace(/>/g,'&gt;');
}

var header =
  '<!doctype html>\n' +
  '<head><meta charset="utf-8"></head>\n' +
  '<html><body>\n\n';

var footer =
  '\n\n' +
  '</body></html>\n';

var assert = require('assert');

var jsonml = require('./jsonml');

module.exports = function formatText(text, options) {
  var json = jsonml.formatJson(text, options);

  var elements = json.map(formatNode);
  var output = elements.join('\n\n') + '\n';

  if (options.standalone)
    output = header + output + footer;
  return output;
};

var formatNode = function(node) {
  if (isString(node))
    return escape(node);

  var tag = node.shift();

  var attr = '';
  if (node.length > 0 && isObject(node[0])) {
    attr = formatAttributes(node.shift());
  }

  var children = node.map(formatNode);

  return '<' + tag + attr + '>' + children.join('') + '</' + tag + '>';
};

var formatAttributes = function(attr) {
  var result = '';
  for (var key in attr) {
    result += ' ' + key + '="' + attr[key] + '"';
  }
  return result;
};

var isString = function(obj) { return obj.constructor === String; };
var isObject = function(obj) { return obj.constructor === Object; };

var escape = function(str) {
  return str.
    replace(/&/g,'&amp;').
    replace(/</g,'&lt;').
    replace(/>/g,'&gt;');
};

var header =
  '<!doctype html>\n' +
  '<head><meta charset="utf-8"></head>\n' +
  '<html><body>\n\n';

var footer =
  '\n\n' +
  '</body></html>\n';

Implement conversion to HTML via JsonML.