/*
 * localemap - map win32 locale names to ICU standard names
 *
 * Copyright (C) 2005, PostgreSQL Global Development Group
 *
 * $PostgreSQL$
 */
#include "postgres.h" 

#include "localemap.h"


static char *match_language(char *winlanguage)
{
	_keyval *kv;

	for (kv = iso639; kv->key; kv++) {
		if (!strcasecmp(kv->key, winlanguage))
			return kv->val;
	}
	ereport(ERROR,
			(errmsg("could not match language for %s", winlanguage)));
	return NULL;
}

static char *match_country(char *wincountry)
{
	_keyval *kv;

	for (kv = iso3166; kv->key; kv++) {
		if (!strcasecmp(kv->key, wincountry))
			return kv->val;
	}
	return NULL;
}

/*
 * Attempt to convert a win32 locale (Swedish_Sweden.1252)
 * to ICU format (sv_se)
 */
static char outbuf[16];
char *pgwin32_localemap(char *winlocale)
{
	char buf[256];
	char *underscore;
	char *dot;
	char *country;

	if (strlen(winlocale)>255) 
		ereport(ERROR,
				(errmsg_internal("locale name too long")));
	strcpy(buf,winlocale);

	underscore = strchr(buf,'_');
	if (!underscore)
		/* Only language name */
		return match_language(buf);

	*underscore = 0;
	underscore++;

	dot = strchr(underscore,'.');
	if (dot)
		/* If codepage is included, we just ignore it. */
		*dot = 0;
	
	country = match_country(underscore);
	if (!country)
		return match_language(buf);

	sprintf(outbuf,"%s_%s",match_language(buf),country);
	return outbuf;
}
