package com.atlassian.stash.internal.language;

import com.atlassian.plugin.PluginAccessor;
import com.atlassian.stash.internal.plugin.LanguageModuleDescriptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Nonnull;
import java.util.*;

import static com.atlassian.bitbucket.util.Chainable.chain;

@Service("languageService")
public class PluginLanguageService implements InternalLanguageService {

    private final PluginAccessor pluginAccessor;

    @Autowired
    public PluginLanguageService(PluginAccessor pluginAccessor) {
        this.pluginAccessor = pluginAccessor;
    }

    @Nonnull
    @Override
    public SortedSet<Language> getLanguages() {
        // Return a unique Set of locales - if two plugins provide the same locale then combine them
        // We want the order to always be consistent for UI and locale resolution consistency
        SortedSet<Language> languages = new TreeSet<>();
        for (LanguageModuleDescriptor descriptor : pluginAccessor.getEnabledModuleDescriptorsByClass(LanguageModuleDescriptor.class)) {
            // Unfortunately Language (in service-api) isn't accessible from platform
            languages.add(new Language(descriptor.getModule()));
        }

        return Collections.unmodifiableSortedSet(languages);
    }
}
