package lc.mecha.nls;

import java.util.*;

/**
 * Stores a bundle of NLS messages.
 *
 * @author Alex Leigh
 */
public class NlsMessageBundle {
    private final HashMap<Locale, HashMap<String, HashMap<Integer, NlsMessage>>> msgs = new HashMap<>();
    private final Locale defaultLocale = Locale.US;
    private final HashSet<Locale> locales = new HashSet<>();

    public NlsMessage getMessage(String code, int number, Locale locale) {
        HashMap<String, HashMap<Integer, NlsMessage>> localeMsgs = msgs.get(locale);
        if (localeMsgs == null) {
            localeMsgs = msgs.get(defaultLocale);
        }

        if (localeMsgs != null) {
            HashMap<Integer, NlsMessage> codeMsgs = localeMsgs.get(code);
            if (codeMsgs != null) {
                NlsMessage msg = codeMsgs.get(number);
                if (msg != null) return msg;
            }
        }

        // TODO: Provide a Locale-specific unknown-message
        return unknownMessage(code, number);
    }

    private NlsMessage unknownMessage(String code, int number) {
        NlsMessage msg = new NlsMessage(code, number, "Unknown Message");
        return msg;
    }

    public void putMessage(NlsMessage msg, Locale locale) {
        locales.add(locale);

        HashMap<String, HashMap<Integer, NlsMessage>> localeMsgs = msgs.get(locale);
        if (localeMsgs == null) {
            localeMsgs = new HashMap<String, HashMap<Integer, NlsMessage>>();
            msgs.put(locale, localeMsgs);
        }

        HashMap<Integer, NlsMessage> codeMsgs = localeMsgs.get(msg.getCode());
        if (codeMsgs == null) {
            codeMsgs = new HashMap<Integer, NlsMessage>();
            localeMsgs.put(msg.getCode(), codeMsgs);
        }

        codeMsgs.put(msg.getNumber(), msg);
    }

    public Set<Locale> getLocales() {
        return Collections.unmodifiableSet(locales);
    }
}
