/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jetbrains.buildServer.agent.android.tools;

import com.intellij.execution.ExecutionException;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.agent.android.NonZeroExitCodeException;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

public class JavacTool extends AbstractTool {
  @NonNls @NotNull private static final String JAVA_SUFFIX = ".java";
  @NonNls @NotNull private static final String JAR_SUFFIX = ".jar";
  @NotNull private final String myAndroidJarPath;

  public JavacTool(@NotNull final String toolPath, @NotNull final String androidJarPath, @NotNull final BuildRunnerContext context) {
    super(toolPath, context);
    myAndroidJarPath = androidJarPath;
  }

  @NotNull
  public File compileSources(@NotNull final File tempDir,
                             @NotNull final File rFileRootDir,
                             @NotNull final String[] sourcesDirs,
                             @NotNull final String[] nativeLibsDirs,
                             @NotNull final String additionalOptions) throws IOException, ExecutionException, NonZeroExitCodeException {
    final File tempOutputRootDir = FileUtil.createTempDirectory("___", "", tempDir);

    final List<String> argsBefore = new ArrayList<String>();
    if (isDebug()) {
      argsBefore.add("-verbose");
    }
    Collections.addAll(argsBefore, "-classpath", findJars(nativeLibsDirs));
    Collections.addAll(argsBefore, "-sourcepath", createSourcePath(rFileRootDir, sourcesDirs));
    Collections.addAll(argsBefore, "-d", tempOutputRootDir.getAbsolutePath());

    execute(argsBefore, Collections.singletonList("@" + collectSources(tempDir, rFileRootDir, sourcesDirs).getAbsolutePath()), additionalOptions);

    return tempOutputRootDir;
  }

  @NotNull
  private String findJars(@NotNull final String[] nativeLibsDirs) throws IOException {
    final StringBuilder sb = new StringBuilder(myAndroidJarPath);
    final FileProcessor processor = new FileProcessor() {
      public void process(@NotNull final File file) {
        sb.append(";").append(file.getAbsolutePath());
      }
    };
    for (final String nativeLibsDir : nativeLibsDirs) {
      processFiles(JAR_SUFFIX, new File(nativeLibsDir), processor);
    }
    return sb.toString();
  }

  @NotNull
  private static String createSourcePath(@NotNull final File rFileRootDir, @NotNull final String[] sourcesDirs) {
    final StringBuilder sb = new StringBuilder(rFileRootDir.getAbsolutePath());
    for (final String sourcesDir : sourcesDirs) {
      sb.append(";").append(sourcesDir);
    }
    return sb.toString();
  }

  @NotNull
  private static File collectSources(@NotNull final File tempDir, @NotNull final File rFileRootDir, @NotNull final String[] sourcesDirs) throws IOException {
    final File listFile = FileUtil.createTempFile(tempDir, "", "", true);

    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(listFile)));

    final FileProcessor processor = new FileProcessor() {
      public void process(@NotNull final File file) throws IOException {
        writer.write(file.getAbsolutePath());
        writer.newLine();
      }
    };

    try {
      processFiles(JAVA_SUFFIX, rFileRootDir, processor);
      for (final String sourcesDir : sourcesDirs) {
        processFiles(JAVA_SUFFIX, new File(sourcesDir), processor);
      }
    }
    finally {
      writer.close();
    }

    return listFile;
  }

  private static void processFiles(@NotNull final String suffix, @NotNull final File dir, @NotNull final FileProcessor processor) throws IOException {
    final File[] files = dir.listFiles();
    if (files == null) return;
    for (final File child : files) {
      if (child.isFile() && child.getName().endsWith(suffix)) {
        processor.process(child);
      }
      else if (child.isDirectory()) {
        processFiles(suffix, child, processor);
      }
    }
  }

  private static interface FileProcessor {
    void process(@NotNull File file) throws IOException;
  }
}
