package com.atlassian.stash.internal.i18n;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.LocaleUtils;

import java.util.List;
import java.util.Locale;

/**
 * Builder for appending locales and removing duplicates as we go.
 */
public class LocaleBuilder {

    private final List<Locale> locales = Lists.newArrayList();

    public LocaleBuilder add(Locale locale) {
        if (locale != null) {
            addSubLocales(locale);
        }
        return this;
    }

    public LocaleBuilder addAll(Iterable<Locale> locales) {
        for (Locale locale : locales) {
            add(locale);
        }
        return this;
    }

    public List<Locale> build() {
        return locales;
    }

    private void addSubLocales(Locale locale) {
        for (Locale subLocale : LocaleUtils.localeLookupList(locale)) {
            // Given the small number of inputs this is actually faster than keeping a cache
            if (locales.contains(subLocale)) {
                return;
            }
            locales.add(subLocale);
        }
    }
}
