/*
 * @author: Eugene Zhuravlev
 * Date: Feb 5, 2003
 * Time: 4:17:58 PM
 */
package com.intellij.compiler.impl;

import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.vfs.VirtualFile;
import gnu.trove.THashSet;

import java.util.*;

public class CompositeScope extends UserDataHolderBase implements CompileScope{
  private final List<CompileScope> myScopes = new ArrayList<CompileScope>();

  public CompositeScope(CompileScope scope1, CompileScope scope2) {
    myScopes.add(scope1);
    myScopes.add(scope2);
  }

  public CompositeScope(CompileScope[] scopes) {
    myScopes.addAll(Arrays.asList(scopes));
  }

  public VirtualFile[] getFiles(FileType fileType, boolean inSourceOnly) {
    Set<VirtualFile> allFiles = new THashSet<VirtualFile>();
    for (CompileScope scope : myScopes) {
      final VirtualFile[] files = scope.getFiles(fileType, inSourceOnly);
      if (files.length > 0) {
        allFiles.addAll(Arrays.asList(files));
      }
    }
    return allFiles.toArray(new VirtualFile[allFiles.size()]);
  }

  public boolean belongs(String url) {
    for (CompileScope scope : myScopes) {
      if (scope.belongs(url)) {
        return true;
      }
    }
    return false;
  }

  public Module[] getAffectedModules() {
    Set<Module> modules = new HashSet<Module>();
    for (final CompileScope compileScope : myScopes) {
      modules.addAll(Arrays.asList(compileScope.getAffectedModules()));
    }
    return modules.toArray(new Module[modules.size()]);
  }

  public <T> T getUserData(Key<T> key) {
    for (CompileScope compileScope : myScopes) {
      T userData = compileScope.getUserData(key);
      if (userData != null) {
        return userData;
      }
    }
    return super.getUserData(key);
  }
}

@@ -660,36 +660,32 @@
 ope2) %7B%0A    
-my
+add
 Scope
-s.add
 (scope1);%0A  
@@ -686,28 +686,24 @@
 1);%0A    
-my
+add
 Scope
-s.add
 (scope2)
@@ -766,47 +766,385 @@
     
-myScopes.addAll(Arrays.asList(scopes));
+for (CompileScope scope : scopes) %7B%0A      addScope(scope);%0A    %7D%0A  %7D%0A%0A  private void addScope(CompileScope scope) %7B%0A    if (scope instanceof CompositeScope) %7B%0A      final CompositeScope compositeScope = (CompositeScope)scope;%0A      for (CompileScope childScope : compositeScope.myScopes) %7B%0A        addScope(childScope);%0A      %7D%0A    %7D%0A    else %7B%0A      myScopes.add(scope);%0A    %7D
 %0A  %7D

make optimization