package org.metaborg.sunshine.common;

import java.util.Collection;

import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.language.ILanguageDiscoveryService;
import org.metaborg.core.resource.IResourceService;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;

public class LanguageLoader {
    private final IResourceService resourceService;
    private final ILanguageDiscoveryService languageDiscoveryService;


    @Inject public LanguageLoader(IResourceService resourceService, ILanguageDiscoveryService languageDiscoveryService) {
        this.resourceService = resourceService;
        this.languageDiscoveryService = languageDiscoveryService;
    }


    public Iterable<ILanguageComponent> discoverLanguages(Iterable<String> paths) throws MetaborgException {
        final Collection<FileObject> languageLocations = Lists.newLinkedList();
        try {
            for(String path : paths) {
                final FileObject location = resourceService.resolve(path);
                if(!location.exists()) {
                    final String message = String.format("Cannot discover languages at %s, it does not exist", path);
                    throw new MetaborgException(message);
                }
                languageLocations.add(location);
            }
        } catch(Exception e) {
            final String message = "Discovering languages failed unexpectedly";
            throw new MetaborgException(message, e);
        }

        final Collection<ILanguageComponent> components = Lists.newLinkedList();
        for(FileObject location : languageLocations) {
            Iterables.addAll(components, languageDiscoveryService.discover(languageDiscoveryService.request(location)));
        }

        if(components.isEmpty()) {
            throw new MetaborgException("No languages were discovered");
        }

        return components;
    }
}

@@ -60,16 +60,38 @@
 lection;
+%0Aimport java.util.Set;
 %0A%0Aimport
@@ -343,52 +343,8 @@
 e;%0A%0A
-import com.google.common.collect.Iterables;%0A
 impo
@@ -379,16 +379,55 @@
 .Lists;%0A
+import com.google.common.collect.Sets;%0A
 import c
@@ -673,16 +673,24 @@
 Service,
+%0A       
  ILangua
@@ -869,24 +869,19 @@
  public 
-Iterable
+Set
 %3CILangua
@@ -1657,26 +1657,19 @@
   final 
-Collection
+Set
 %3CILangua
@@ -1694,34 +1694,30 @@
 nents = 
-Lis
+Se
 ts.new
-LinkedLis
+HashSe
 t();%0A   
@@ -1784,103 +1784,76 @@
     
-Iterables.addAll(components, languageDiscoveryService.discover(languageDiscoveryService.request
+components.addAll(languageDiscoveryService.scanComponentsInDirectory
 (loc
@@ -1859,17 +1859,16 @@
 cation))
-)
 ;%0A      

Use new language discovery interface.