#if defined(ENABLE_WWW)

#include <string.h>
#include <time.h>
#include <stdlib.h>
#include "bbs.h"

extern struct bbs_config conf;

char *www_blog() {
	stralloc page = EMPTY_STRALLOC;
	struct ptr_vector entries = blog_load();

	stralloc_copys(&page, "<div class=\"content-header\"><h2>System Blog</h2></div>\n");

	if (ptr_vector_len(&entries) == 0) {
		stralloc_cats(&page, "<p>No Entries</p>\n");
		stralloc_0(&page);
		return page.s;
	}
	for (size_t i = 0; i < ptr_vector_len(&entries); i++) {
		struct blog_entry_t *entry = ptr_vector_get(&entries, i);
		struct tm entry_time;
		int hour;
		char timebuf[16];
		char datebuf[24];

		localtime_r(&entry->date, &entry_time);
		hour = entry_time.tm_hour;
		strftime(timebuf, sizeof timebuf, "%l:%M", &entry_time);
		strftime(datebuf, sizeof datebuf, " %a, %e %b %Y", &entry_time);

		stralloc_cats(&page, "<div class=\"blog-header\"><div class=\"blog-title\"><h3>");
		stralloc_cats(&page, entry->subject);
		stralloc_cats(&page, "</h3></div><div class=\"blog-date\">");
		stralloc_cats(&page, timebuf);
		stralloc_cats(&page, hour >= 12 ? "pm" : "am");
		stralloc_cats(&page, datebuf);
		stralloc_cats(&page, "</div><div class=\"blog-author\">by ");
		stralloc_cats(&page, entry->author);
		stralloc_cats(&page, "</div></div>");

		stralloc_cats(&page, "<div class=\"blog-entry\"><p>");

		for (char *p = entry->body; *p != '\0'; ++p) {
			if (*p != '\r') {
				stralloc_append1(&page, *p);
				continue;
			}
			if (p[1] != '\0' && p[1] != '\r') {
				stralloc_append1(&page, ' ');
				continue;
			}
			++p;
			stralloc_cats(&page, "</p><p>");
		}
		stralloc_cats(&page, "</p></div>");
	}
	ptr_vector_apply(&entries, free);
	destroy_ptr_vector(&entries);
	stralloc_0(&page);

	return page.s;
}

#endif
