package com.atlassian.stash.internal.i18n;

import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Collection;

import static com.google.common.collect.Collections2.filter;
import static com.google.common.collect.Collections2.transform;

/**
 * A {@link MessageSource message source} that looks for message bundles on the classpath to calculate the
 * {@link #setBasenames(String...) basenames} used for message lookups.
 */
public class ClasspathI18nMessageSource extends ResourceBundleMessageSource {

    public ClasspathI18nMessageSource() throws IOException {
        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        ImmutableList<Resource> resources = ImmutableList.<Resource>builder()
                .add(patternResolver.getResources("classpath*:/i18n/stash-*.properties"))
                .add(patternResolver.getResources("classpath*:/i18n/bitbucket-*.properties"))
                .build();

        Collection<String> baseNames = filter(transform(resources, new Function<Resource, String>() {

            @Override
            public String apply(Resource resource) {
                String name = resource.getFilename();
                return "i18n/" + name.substring(0, name.length() - ".properties".length());
            }
        }), Predicates.notNull());

        if (!baseNames.isEmpty()) {
            setBasenames(baseNames.toArray(new String[baseNames.size()]));
        }
    }
}
