package main

import (
	"net/http"
)

func init() {
	for short, long := range short2Long {
		long2Short[long] = short
	}
}

var short2Long = map[string]string{
	"ar":    "ar-sa",
	"bg":    "bg-bg",
	"cs":    "cs-cz",
	"da":    "da-dk",
	"de":    "de-de",
	"el":    "el-gr",
	"en":    "en-us",
	"es":    "es-es",
	"es-mx": "es-mx",
	"fi":    "fi-fi",
	"fr":    "fr-fr",
	"hu":    "hu-hu",
	"it":    "it-it",
	"ja":    "ja-jp",
	"ko":    "ko-kr",
	"nl":    "nl-nl",
	"no":    "no-no",
	"pl":    "pl-pl",
	"pt-br": "pt-br",
	"pt":    "pt-pt",
	"ru":    "ru-ru",
	"sk":    "sk-sk",
	"sv":    "sv-se",
	"th":    "th-th",
	"tr":    "tr-tr",
	"vi":    "vi-vn",
	"zh-cn": "zh-cn",
	"zh-tw": "zh-tw",
}

var (
	langParam     = "language"
	langCookie    = "language"
	defaultLocale = newLocale("en")
	long2Short    = map[string]string{}
)

// Locale is a language used to translate the website. Locales have both a short ("en") and
// long representation ("en-us")
type Locale struct {
	Short    string
	Long     string
	Original string
}

func newLocale(locale string) Locale {
	l := Locale{
		Original: locale,
	}

	if short2Long[locale] != "" {
		l.Short = locale
		l.Long = short2Long[locale]
	}

	if long2Short[locale] != "" {
		l.Short = long2Short[locale]
		l.Long = locale
	}

	return l
}

func requestLocale(r *http.Request) Locale {
	priorities := localePriorities(r)

	for _, locale := range priorities {
		if _, ok := long2Short[locale.Long]; ok {
			return locale
		}
	}

	return defaultLocale
}

func localePriorities(r *http.Request) []Locale {
	var priorities []Locale

	language := r.URL.Query().Get(langParam)
	if len(language) > 0 {
		priorities = append(priorities, newLocale(language))
	}

	cookie, err := r.Cookie(langCookie)
	if err == nil {
		priorities = append(priorities, newLocale(cookie.Value))
	}

	priorities = append(priorities, defaultLocale)

	return priorities
}
