#pragma once

#include "log.qh"
#include "map.qh"
#include "unsafe.qh"

// translation helpers
string prvm_language;

/**
 * @deprecated prefer _("translatable text") - GMQCC's -ftranslatable-strings feature
 */
ERASEABLE
string language_filename(string s)
{
	string fn = prvm_language;
	if (fn == "" || fn == "en" || fn == "dump")
		return s;
	fn = strcat(s, ".", fn);
	int fh = fopen(fn, FILE_READ);
	if (fh >= 0)
	{
		fclose(fh);
		return fn;
	}
	return s;
}

#ifndef CTX_CACHE
	#define CTX_CACHE 1
#endif

#if CTX_CACHE
	HashMap CTX_cache;
	STATIC_INIT(CTX_cache)
	{
		HM_NEW(CTX_cache);
	}
	SHUTDOWN(CTX_cache)
	{
		HM_DELETE(CTX_cache);
	}
#endif

ERASEABLE
string CTX(string s)
{
#if CTX_CACHE
	string c = HM_gets(CTX_cache, s);
	if (c != "")
		return c;
#endif
	int caret_ofs = strstrofs(s, "^", 0);
	string ret = s;
	// empty (caret_ofs == 0) and one char (caret_ofs == 1) prefixes are invalid
	if (caret_ofs > 1)
	{
		int space_ofs = strstrofs(substring(s, 0, caret_ofs), " ", 0);
		// prefixes containing a space are invalid (likely the caret is part of a color code)
		if (space_ofs < 0 || space_ofs > caret_ofs)
			ret = substring(s, caret_ofs + 1, -1);
	}
#if CTX_CACHE
	LOG_DEBUGF("CTX(\"%s\")", s);
	HM_sets(CTX_cache, s, ret);
#endif
	return ret;
}

#define ZCTX(s) strzone(CTX(s))
