#include <h/mh.h>
#include <h/utils.h>
#include <h/addrsbr.h>

static char *threadid(char *, char *);

char *
getthreadid(const char *path)
{
	char *msgid = NULL;
	char *referens = NULL;
	char *ret;
	struct field f = {{0}};
	enum state state = FLD2;
	FILE *file = fopen(path, "r");

	while (state == FLD2 && !msgid && !referens) {
		switch (state = m_getfld2(state, &f, file)) {
		case FLD2:
			if (strncasecmp("message-id", f.name, f.namelen)==0) {
				msgid = f.value;
				f.value = NULL;
			} else if (strncasecmp("references", f.name, f.namelen)==0) {
				referens = f.value;
				f.value = NULL;
			}
			break;
		default:
			fclose(file);
			break;
		}
	}

	ret = threadid(msgid, referens);

	mh_free0(&msgid);
	mh_free0(&referens);

	return ret;
}

static char *
threadid(char *msgid, char *referens)
{
	char *threadfrom;
	char *start, *end;
	char *cp;

	threadfrom = referens ? referens : msgid;
	if (!threadfrom) {
		return NULL;
	}

	start = strchr(threadfrom, '<');
	end = strchr(start, '>');
	if (!(*start) || !(*end)) {
		return NULL;
	}
	*end = '\0';
	cp = mh_xstrdup(start + 1);
	*end = '>';

	return cp;
}
