/*
 * Copyright (c) 2016-2017 Daniel Ennis (Aikar) - MIT License
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package co.aikar.commands;

import co.aikar.locales.LocaleManager;
import co.aikar.locales.MessageKey;
import co.aikar.locales.MessageKeyProvider;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;

@SuppressWarnings("WeakerAccess")
public class Locales {
    // Locales for reference since Locale doesn't have as many, add our own here for ease of use.
    public static final Locale ENGLISH = Locale.ENGLISH;
    public static final Locale GERMAN = Locale.GERMAN;
    public static final Locale FRENCH = Locale.FRENCH;
    public static final Locale JAPANESE = Locale.JAPANESE;
    public static final Locale ITALIAN = Locale.ITALIAN;
    public static final Locale KOREAN = Locale.KOREAN;
    public static final Locale CHINESE = Locale.CHINESE;
    public static final Locale SIMPLIFIED_CHINESE = Locale.SIMPLIFIED_CHINESE;
    public static final Locale TRADITIONAL_CHINESE = Locale.TRADITIONAL_CHINESE;
    public static final Locale SPANISH = new Locale("es");
    public static final Locale DUTCH = new Locale("nl");
    public static final Locale DANISH = new Locale("da");
    public static final Locale CZECH = new Locale("cs");
    public static final Locale GREEK = new Locale("el");
    public static final Locale LATIN = new Locale("la");
    public static final Locale BULGARIAN = new Locale("bg");
    public static final Locale AFRIKAANS = new Locale("af");
    public static final Locale HINDI = new Locale("hi");
    public static final Locale HEBREW = new Locale("he");
    public static final Locale POLISH = new Locale("pl");
    public static final Locale PORTUGUESE = new Locale("pt");
    public static final Locale FINNISH = new Locale("fi");
    public static final Locale SWEDISH = new Locale("sv");
    public static final Locale RUSSIAN = new Locale("ru");
    public static final Locale ROMANIAN = new Locale("ro");
    public static final Locale VIETNAMESE = new Locale("vi");
    public static final Locale THAI = new Locale("th");
    public static final Locale TURKISH = new Locale("tr");
    public static final Locale UKRANIAN = new Locale("uk");
    public static final Locale ARABIC = new Locale("ar");
    public static final Locale WELSH = new Locale("cy");


    private final CommandManager<?, ?, ?> manager;
    private final LocaleManager<CommandIssuer> localeManager;
    private final SetMultimap<String, Locale> loadedBundles = HashMultimap.create();

    public Locales(CommandManager manager) {
        this.manager = manager;
        this.localeManager = LocaleManager.create(manager::getIssuerLocale);
    }

    public void loadLanguages() {
        addMessageBundles("acf-core");
    }

    public Locale getDefaultLocale() {
        return this.localeManager.getDefaultLocale();
    }

    public Locale setDefaultLocale(Locale locale) {
        return this.localeManager.setDefaultLocale(locale);
    }

    /**
     * Looks for all previously loaded bundles, and if any new Supported Languages have been added, load them.
     */
    public void loadMissingBundles() {
        for (Locale locale : manager.getSupportedLanguages()) {
            for (String bundleName : loadedBundles.keys()) {
                addMessageBundle(bundleName, locale);
            }
        }
    }

    public void addMessageBundles(String... bundleNames) {
        for (String bundleName : bundleNames) {
            for (Locale locale : manager.getSupportedLanguages()) {
                addMessageBundle(bundleName, locale);
            }
        }
    }

    public void addMessageBundle(String bundleName, Locale locale) {
        if (!loadedBundles.containsEntry(bundleName, locale)) {
            loadedBundles.put(bundleName, locale);
            this.localeManager.addMessageBundle(bundleName, locale);
        }
    }

    public void addMessageStrings(Locale locale, @NotNull Map<String, String> messages) {
        Map<MessageKey, String> map = new HashMap<>(messages.size());
        messages.forEach((key, value) -> map.put(MessageKey.of(key), value));
        addMessages(locale, map);
    }
    public void addMessages(Locale locale, @NotNull Map<MessageKey, String> messages) {
        this.localeManager.addMessages(locale, messages);
    }

    public String addMessage(Locale locale, MessageKey key, String message) {
        return this.localeManager.addMessage(locale, key, message);
    }

    public String getMessage(CommandIssuer issuer, MessageKeyProvider key) {
        final MessageKey msgKey = key.getMessageKey();
        String message = this.localeManager.getMessage(issuer, msgKey);
        if (message == null) {
            manager.log(LogLevel.ERROR, "Missing Language Key: " + msgKey.getKey());
            message = "<MISSING_LANGUAGE_KEY:" + msgKey.getKey() + ">";
        }
        return message;
    }

    public String replaceI18NStrings(String message) {
        if (message == null) {
            return null;
        }
        Matcher matcher = ACFPatterns.I18N_STRING.matcher(message);
        if (!matcher.matches()) {
            return message;
        }

        CommandIssuer issuer = CommandManager.getCurrentCommandIssuer();

        matcher.reset();
        StringBuffer sb = new StringBuffer(message.length());
        while (matcher.find()) {
            MessageKey key = MessageKey.of(matcher.group("key"));
            matcher.appendReplacement(sb, Matcher.quoteReplacement(getMessage(issuer, key)));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}

@@ -1393,24 +1393,63 @@
 etMultimap;%0A
+import com.google.common.collect.Sets;%0A
 import org.j
@@ -4514,16 +4514,32 @@
 eName : 
+Sets.newHashSet(
 loadedBu
@@ -4547,24 +4547,25 @@
 dles.keys())
+)
  %7B%0A         

Fix CoMoEx in loadMissingBundles