/*
 * HTML from feeds, turned into something to show: Pango markup for the
 * article view, plain text for summaries. libxml2's HTML parser copes with
 * what feeds contain (unclosed tags, stray entities).
 */
#include <libxml/HTMLparser.h>
#include <libxml/tree.h>
#include <pango/pango.h>
#include <string.h>
#include "news.h"

#define MARKUP_MAX (400 * 1024)

static const int parse_flags = HTML_PARSE_RECOVER | HTML_PARSE_NOERROR |
	HTML_PARSE_NOWARNING | HTML_PARSE_NONET | HTML_PARSE_NOBLANKS;

static bool is(const xmlNode *n, const char *name) {
	return n->type == XML_ELEMENT_NODE && strcmp((const char *)n->name, name) == 0;
}

static bool in_list(const xmlNode *n, const char *const *names) {
	for (; *names; names++) {
		if (is(n, *names)) {
			return true;
		}
	}
	return false;
}

static const char *const skipped[] = { "script", "style", "head", "noscript",
	"iframe", "svg", "form", "button", "nav", "footer", "object", "embed",
	"select", "template", NULL };
static const char *const blocks[] = { "p", "div", "section", "article",
	"aside", "header", "main", "figure", "figcaption", "ul", "ol", "table",
	"tr", "dl", "dd", "dt", "pre", "address", "hr", "details", NULL };

/* Parses fragments as a body */
static htmlDocPtr parse(const char *html) {
	return htmlReadMemory(html, (int)strlen(html), NULL, "UTF-8", parse_flags);
}

static char *prop(xmlNode *n, const char *name) {
	xmlChar *v = xmlGetProp(n, (const xmlChar *)name);
	char *out = v ? g_strdup((const char *)v) : NULL;
	if (v) {
		xmlFree(v);
	}
	return out;
}

/* Markup */

struct md {
	GString *out;
	char *image;
	bool pre;
	int list_depth;
};

/* Ends the paragraph so far: a blank line, but never at the very start and
 * never twice */
static void para(struct md *m) {
	GString *o = m->out;
	if (o->len == 0 || (o->len >= 2 && o->str[o->len - 1] == '\n' &&
			o->str[o->len - 2] == '\n')) {
		return;
	}
	if (o->str[o->len - 1] != '\n') {
		g_string_append_c(o, '\n');
	}
	g_string_append_c(o, '\n');
}

static void line(struct md *m) {
	GString *o = m->out;
	if (o->len > 0 && o->str[o->len - 1] != '\n') {
		g_string_append_c(o, '\n');
	}
}

static void add_text(struct md *m, const char *text) {
	GString *o = m->out;
	if (m->pre) {
		char *esc = g_markup_escape_text(text, -1);
		g_string_append(o, esc);
		g_free(esc);
		return;
	}
	/* Runs of white space are one space; none at the start of a line */
	GString *clean = g_string_new(NULL);
	bool space = o->len == 0 || o->str[o->len - 1] == '\n' ||
		o->str[o->len - 1] == ' ';
	for (const char *p = text; *p; p = g_utf8_next_char(p)) {
		gunichar c = g_utf8_get_char(p);
		if (c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == 0xa0) {
			if (!space) {
				g_string_append_c(clean, ' ');
				space = true;
			}
		} else {
			g_string_append_unichar(clean, c);
			space = false;
		}
	}
	char *esc = g_markup_escape_text(clean->str, clean->len);
	g_string_append(o, esc);
	g_free(esc);
	g_string_free(clean, TRUE);
}

static void walk(struct md *m, xmlNode *n) {
	for (; n; n = n->next) {
		if (m->out->len > MARKUP_MAX) {
			return;
		}
		if (n->type == XML_TEXT_NODE || n->type == XML_CDATA_SECTION_NODE) {
			add_text(m, (const char *)n->content);
			continue;
		}
		if (n->type != XML_ELEMENT_NODE) {
			continue;
		}
		if (in_list(n, skipped)) {
			continue;
		}
		if (is(n, "img")) {
			if (m->image == NULL) {
				char *src = prop(n, "src");
				char *w = prop(n, "width"), *h = prop(n, "height");
				/* Not a tracking pixel or an icon */
				if (src && src[0] && !(w && atoi(w) > 0 && atoi(w) < 40) &&
						!(h && atoi(h) > 0 && atoi(h) < 40)) {
					m->image = g_strdup(src);
				}
				g_free(w);
				g_free(h);
				g_free(src);
			}
			continue;
		}
		if (is(n, "br")) {
			g_string_append_c(m->out, '\n');
			continue;
		}
		const char *open = NULL, *close = NULL;
		bool block = in_list(n, blocks);
		bool saved_pre = m->pre;
		if (is(n, "b") || is(n, "strong")) {
			open = "<b>", close = "</b>";
		} else if (is(n, "i") || is(n, "em") || is(n, "cite")) {
			open = "<i>", close = "</i>";
		} else if (is(n, "u") || is(n, "ins")) {
			open = "<u>", close = "</u>";
		} else if (is(n, "s") || is(n, "del") || is(n, "strike")) {
			open = "<s>", close = "</s>";
		} else if (is(n, "sup")) {
			open = "<sup>", close = "</sup>";
		} else if (is(n, "sub")) {
			open = "<sub>", close = "</sub>";
		} else if (is(n, "code") || is(n, "tt") || is(n, "kbd") || is(n, "samp")) {
			open = "<tt>", close = "</tt>";
		} else if (is(n, "a")) {
			open = "<u>", close = "</u>";
		} else if (is(n, "blockquote")) {
			para(m);
			open = "<i>", close = "</i>";
			block = true;
		} else if (n->name[0] == 'h' && n->name[1] >= '1' && n->name[1] <= '6' &&
				n->name[2] == '\0') {
			para(m);
			open = n->name[1] <= '2' ? "<span size=\"x-large\" weight=\"light\">" :
				"<span size=\"large\" weight=\"bold\">";
			close = "</span>";
			block = true;
		} else if (is(n, "li")) {
			line(m);
			g_string_append(m->out, "• ");
		}
		if (is(n, "pre")) {
			m->pre = true;
			open = "<tt>";
			close = "</tt>";
		}
		if (is(n, "ul") || is(n, "ol")) {
			m->list_depth++;
		}
		if (block && !is(n, "ul") && !is(n, "ol")) {
			para(m);
		}
		if (open) {
			g_string_append(m->out, open);
		}
		walk(m, n->children);
		if (close) {
			g_string_append(m->out, close);
		}
		if (is(n, "ul") || is(n, "ol")) {
			m->list_depth--;
			para(m);
		} else if (is(n, "li")) {
			line(m);
		} else if (block) {
			para(m);
		}
		m->pre = saved_pre;
	}
}

char *html_to_markup(const char *html, char **first_image) {
	if (first_image) {
		*first_image = NULL;
	}
	if (html == NULL || html[0] == '\0') {
		return NULL;
	}
	htmlDocPtr doc = parse(html);
	if (doc == NULL) {
		return NULL;
	}
	struct md m = { .out = g_string_new(NULL) };
	walk(&m, xmlDocGetRootElement(doc));
	xmlFreeDoc(doc);
	/* Trim the ends */
	while (m.out->len > 0 && (m.out->str[m.out->len - 1] == '\n' ||
			m.out->str[m.out->len - 1] == ' ')) {
		g_string_truncate(m.out, m.out->len - 1);
	}
	if (first_image) {
		*first_image = m.image;
	} else {
		g_free(m.image);
	}
	if (m.out->len == 0) {
		g_string_free(m.out, TRUE);
		return NULL;
	}
	/* Unbalanced tags would stop it from being shown as markup at all:
	 * check, and fall back to the text */
	if (!pango_parse_markup(m.out->str, -1, 0, NULL, NULL, NULL, NULL)) {
		g_string_free(m.out, TRUE);
		char *text = html_to_text(html, MARKUP_MAX);
		char *esc = text ? g_markup_escape_text(text, -1) : NULL;
		g_free(text);
		return esc;
	}
	return g_string_free(m.out, FALSE);
}

/* Plain text */

struct tx {
	GString *out;
	size_t max;
};

static void text_walk(struct tx *t, xmlNode *n) {
	for (; n; n = n->next) {
		if (t->out->len >= t->max * 4) {
			return;
		}
		if (n->type == XML_TEXT_NODE || n->type == XML_CDATA_SECTION_NODE) {
			g_string_append(t->out, (const char *)n->content);
			continue;
		}
		if (n->type != XML_ELEMENT_NODE || in_list(n, skipped)) {
			continue;
		}
		bool gap = in_list(n, blocks) || is(n, "br") || is(n, "li") ||
			(n->name[0] == 'h' && n->name[1] >= '1' && n->name[1] <= '6');
		if (gap) {
			g_string_append_c(t->out, ' ');
		}
		text_walk(t, n->children);
		if (gap) {
			g_string_append_c(t->out, ' ');
		}
	}
}

char *html_to_text(const char *html, size_t max) {
	if (html == NULL) {
		return g_strdup("");
	}
	htmlDocPtr doc = parse(html);
	struct tx t = { g_string_new(NULL), max };
	if (doc) {
		text_walk(&t, xmlDocGetRootElement(doc));
		xmlFreeDoc(doc);
	}
	/* One space between words */
	GString *flat = g_string_new(NULL);
	bool space = true;
	size_t chars = 0;
	bool cut = false;
	for (const char *p = t.out->str; *p; p = g_utf8_next_char(p)) {
		if (chars >= max) {
			cut = true;
			break;
		}
		gunichar c = g_utf8_get_char(p);
		if (g_unichar_isspace(c) || c == 0xa0) {
			if (!space) {
				g_string_append_c(flat, ' ');
				space = true;
			}
			continue;
		}
		g_string_append_unichar(flat, c);
		space = false;
		chars++;
	}
	g_string_free(t.out, TRUE);
	while (flat->len > 0 && flat->str[flat->len - 1] == ' ') {
		g_string_truncate(flat, flat->len - 1);
	}
	if (cut) {
		/* At a word, not through one */
		char *sp = strrchr(flat->str, ' ');
		if (sp && (size_t)(sp - flat->str) > flat->len / 2) {
			g_string_truncate(flat, sp - flat->str);
		}
		g_string_append(flat, "…");
	}
	return g_string_free(flat, FALSE);
}

/* Feed autodiscovery: <link rel="alternate" type="application/rss+xml"> */

static xmlNode *find_feed_link(xmlNode *n) {
	for (; n; n = n->next) {
		if (is(n, "link")) {
			char *rel = prop(n, "rel"), *type = prop(n, "type");
			bool hit = rel && type && g_ascii_strcasecmp(rel, "alternate") == 0 &&
				(g_ascii_strcasecmp(type, "application/rss+xml") == 0 ||
				g_ascii_strcasecmp(type, "application/atom+xml") == 0);
			g_free(rel);
			g_free(type);
			if (hit) {
				return n;
			}
		}
		xmlNode *found = find_feed_link(n->children);
		if (found) {
			return found;
		}
	}
	return NULL;
}

char *feed_discover(const char *html, size_t len, const char *base) {
	htmlDocPtr doc = htmlReadMemory(html, (int)len, base, NULL, parse_flags);
	if (doc == NULL) {
		return NULL;
	}
	char *out = NULL;
	xmlNode *link = find_feed_link(xmlDocGetRootElement(doc));
	if (link) {
		char *href = prop(link, "href");
		if (href && href[0]) {
			out = g_uri_resolve_relative(base, href, G_URI_FLAGS_NONE, NULL);
		}
		g_free(href);
	}
	xmlFreeDoc(doc);
	return out;
}
