/*
 * Copyright 2010 the original author or authors.
 *
 * 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 org.gradle.util;

import org.apache.commons.lang.StringUtils;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A JUnit rule which provides a unique temporary folder for the test.
 */
public class TemporaryFolder implements MethodRule, TestFileContext {
    private TestFile dir;
    private String prefix;
    private static TestFile root;
    private static AtomicInteger testCounter = new AtomicInteger(1);

    static {
        // NOTE: the space in the directory name is intentional
        root = new TestFile(new File("build/tmp/test files"));
    }

    public TestFile getDir() {
        if (dir == null) {
            if (prefix == null) {
                // This can happen if this is used in a constructor or a @Before method. It also happens when using
                // @RunWith(SomeRunner) when the runner does not support rules.
                prefix = determinePrefix();
            }
            for (int counter = 1; true; counter++) {
                dir = root.file(counter == 1 ? prefix : String.format("%s%d", prefix, counter));
                if (dir.mkdirs()) {
                    break;
                }
            }
        }
        return dir;
    }

    private String determinePrefix() {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement element : stackTrace) {
            if (element.getClassName().endsWith("Test") || element.getClassName().endsWith("Spec")) {
                return StringUtils.substringAfterLast(element.getClassName(), ".") + "/unknown-test-" + testCounter.getAndIncrement();
            }
        }
        return "unknown-test-class-" + testCounter.getAndIncrement();
    }

    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
        init(method, target);
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                base.evaluate();
                getDir().maybeDeleteDir();
                // Don't delete on failure
            }
        };
    }

    private void init(FrameworkMethod method, Object target) {
        if (prefix == null) {
            String safeMethodName = method.getName().replaceAll("\\s", "_").replace(File.pathSeparator, "_").replace(":", "_");
            if (safeMethodName.length() > 64) {
                safeMethodName = safeMethodName.substring(0, 32) + "..." + safeMethodName.substring(safeMethodName.length() - 32);
            }
            prefix = String.format("%s/%s", target.getClass().getSimpleName(), safeMethodName);
        }
    }

    public static TemporaryFolder newInstance() {
        return new TemporaryFolder();
    }

    public static TemporaryFolder newInstance(FrameworkMethod method, Object target) {
        TemporaryFolder temporaryFolder = new TemporaryFolder();
        temporaryFolder.init(method, target);
        return temporaryFolder;
    }

    public TestFile getTestDir() {
        return getDir();
    }

    public TestFile file(Object... path) {
        return getDir().file((Object[]) path);
    }

    public TestFile createFile(Object... path) {
        return file((Object[]) path).createFile();
    }

    public TestFile createDir(Object... path) {
        return file((Object[]) path).createDir();
    }
}
@@ -710,24 +710,94 @@
 MethodRule;%0A
+import org.junit.rules.TestRule;%0Aimport org.junit.runner.Description;%0A
 import org.j
@@ -1077,16 +1077,26 @@
 hodRule,
+ TestRule,
  TestFil
@@ -2668,32 +2668,69 @@
  init(method
-, target
+.getName(), target.getClass().getSimpleName()
 );%0A        r
@@ -2989,65 +2989,654 @@
    p
-rivate void init(FrameworkMethod method, Object target) %7B
+ublic Statement apply(final Statement base, Description description) %7B%0A        init(description.getMethodName(), description.getTestClass().getSimpleName());%0A        return new Statement() %7B%0A            @Override%0A            public void evaluate() throws Throwable %7B%0A                base.evaluate();%0A                getDir().maybeDeleteDir();%0A                // Don't delete on failure%0A            %7D%0A        %7D;%0A    %7D%0A%0A    private void init(String methodName, String className) %7B%0A        if (methodName == null) %7B%0A            // must be a @ClassRule; use the rule's class name instead%0A            methodName = getClass().getSimpleName();%0A        %7D
 %0A   
@@ -3704,26 +3704,20 @@
 = method
-.get
 Name
-()
 .replace
@@ -4025,41 +4025,17 @@
 s%22, 
-target.getClass().getSimple
+class
 Name
-()
 , sa
@@ -4348,24 +4348,61 @@
 t(method
-, target
+.getName(), target.getClass().getSimpleName()
 );%0A     

implement new TestRule interface so that TemporaryFolder can be used as @ClassRule