#include "markdown.h"

#include <QDebug>
#include <QIODevice>
#ifndef NO_MARKDOWN
extern "C" {
#  include MARKDOWN_HEADER
}
#  ifndef mkd_flags_are
#	ifndef MKD_DLEXTRA
#	  define MKD_DLEXTRA 0x01000000
#	endif
#	ifndef MKD_FENCEDCODE
#	  define MKD_FENCEDCODE 0x02000000
#	endif
#	ifndef MKD_EXTRA_FOOTNOTE
#	  define MKD_EXTRA_FOOTNOTE 0x00200000
#	endif
#	ifndef MKD_TOC
#	  define MKD_TOC 0x00001000
#	endif
#	ifndef MKD_AUTOLINK
#	  define MKD_AUTOLINK 0x00004000
#	endif
#	ifndef MKD_GITHUBTAGS
#	  define MKD_GITHUBTAGS 0x08000000
#	endif
#  endif

static QString markdown_css = "table { margin: 5px; background-color: #cccccc; }"
							  "table tr { background-color: white; }"
							  "table td { vertical-align: middle; padding: 5px;}"
							  "table th { padding: 5px; };";

QString md2html(const QByteArray & src) {
	static bool _is_mkd_init = false;
	if (src.isEmpty()) return QString();
	if (!_is_mkd_init) {
		_is_mkd_init = true;
		mkd_initialize();
	}
#  ifdef _MARKDOWN_D
	DWORD flagm = (MKD_DLEXTRA | MKD_FENCEDCODE);
	Document
#  endif
#  ifdef _MKDIO_D
#	ifdef mkd_flags_are
		mkd_flag_t * flagm = mkd_flags();
	mkd_set_flag_num(flagm, MKD_DLEXTRA);
	mkd_set_flag_num(flagm, MKD_FENCEDCODE);
#	else
		mkd_flag_t flagm = (MKD_DLEXTRA | MKD_FENCEDCODE | MKD_GITHUBTAGS | MKD_AUTOLINK);
#	endif
	MMIOT
#  endif
	*doc = mkd_string(src.constData(), src.size(), 0);
	if (!doc) return QString();
	mkd_compile(doc, flagm);
	char * html = 0;
	int len     = mkd_document(doc, &html);
	if (!html) {
		mkd_cleanup(doc);
		return QString();
	}
	QString ret = QString::fromUtf8(html, len);
	mkd_cleanup(doc);
	QString title  = QTextStream(&ret, QIODevice::ReadOnly).readLine();
	title          = title.mid(title.indexOf(">") + 1);
	title          = title.left(title.indexOf("<"));
	QString header = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
					 "<html>\n<head>\n"
					 "<meta name=\"qrichtext\" content=\"1\" />\n"
					 "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
	header.append("<title>" + title + "</title>\n");
	header.append("<style>" + markdown_css + "</style>\n");
	header.append("</head>\n<body>\n");
	ret.prepend(header);
	ret.append("</body>\n</html>\n");
	return ret;
}

#else

QString md2html(const QByteArray & src) {
	return src;
}

#endif
