/*
 * Copyright (C) 2011 Google Inc.
 *
 * 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 com.google.testing.littlemock;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Utility class for helping guess the application data directory.
 */
public class AppDataDirGuesser {

  /** A single default instance of app data dir guesser, for overriding if you really need to. */
  private static volatile AppDataDirGuesser sInjectableInstance = new AppDataDirGuesser();

  public static void setInstance(AppDataDirGuesser instance) {
    sInjectableInstance = instance;
  }

  public static AppDataDirGuesser getsInstance() {
    return sInjectableInstance;
  }

  public File guessSuitableDirectoryForGeneratedClasses() {
    try {
      ClassLoader classLoader = AppDataDirGuesser.class.getClassLoader();
      // Check that we have an instance of the PathClassLoader.
      Class<?> clazz = Class.forName("dalvik.system.PathClassLoader");
      clazz.cast(classLoader);
      // Use the toString() method to calculate the data directory.
      String pathFromThisClassLoader = getPathFromThisClassLoader(classLoader);
      File[] results = guessPath(pathFromThisClassLoader);
      if (results.length > 0) {
        return results[0];
      }
    } catch (ClassCastException e) {
      // Fall through, we will return null.
    } catch (ClassNotFoundException e) {
      // Fall through, we will return null.
    }
    return null;
  }

  private String getPathFromThisClassLoader(ClassLoader classLoader) {
    // Parsing toString() method: yuck.  But no other way to get the path.
    // Strip out the bit between angle brackets, that's our path.
    String result = classLoader.toString();
    int index = result.lastIndexOf('[');
    result = (index == -1) ? result : result.substring(index + 1);
    index = result.indexOf(']');
    return (index == -1) ? result : result.substring(0, index);
  }

  // @VisibleForTesting
  File[] guessPath(String input) {
    List<File> results = new ArrayList<File>();
    for (String potential : input.split(":")) {
      if (!potential.startsWith("/data/app/")) {
        continue;
      }
      int start = "/data/app/".length();
      int end = potential.lastIndexOf(".apk");
      if (end != potential.length() - 4) {
        continue;
      }
      int dash = potential.indexOf("-");
      if (dash != -1) {
        end = dash;
      }
      File file = new File("/data/data/" + potential.substring(start, end) + "/cache");
      if (isWriteableDirectory(file)) {
        results.add(file);
      }
    }
    return results.toArray(new File[results.size()]);
  }

  // @VisibleForTesting
  boolean isWriteableDirectory(File file) {
    return file.isDirectory() && file.canWrite();
  }
}

@@ -650,16 +650,48 @@
 o.File;%0A
+import java.lang.reflect.Field;%0A
 import j
@@ -710,16 +710,16 @@
 ayList;%0A
-
 import j
@@ -1641,16 +1641,26 @@
 Loader =
+%0A         
  getPath
@@ -1655,36 +1655,36 @@
      getPathFrom
-This
+Path
 ClassLoader(clas
@@ -1682,32 +1682,39 @@
 ader(classLoader
+, clazz
 );%0A      File%5B%5D 
@@ -2052,50 +2052,678 @@
 From
-ThisClassLoader(ClassLoader classLoader) %7B
+PathClassLoader(%0A      ClassLoader classLoader, Class%3C?%3E pathClassLoaderClass) %7B%0A    // Prior to ICS, we can simply read the %22path%22 field of the%0A    // PathClassLoader.%0A    try %7B%0A      Field pathField = pathClassLoaderClass.getDeclaredField(%22path%22);%0A      pathField.setAccessible(true);%0A      return (String) pathField.get(classLoader);%0A    %7D catch (NoSuchFieldException e) %7B%0A      // Ignore and fall back on parsing the output of toString below%0A    %7D catch (IllegalAccessException e) %7B%0A      // Ignore and fall back on parsing the output of toString below%0A    %7D catch (ClassCastException e) %7B%0A      // Ignore and fall back on parsing the output of toString below%0A    %7D%0A
 %0A   
@@ -3604,81 +3604,208 @@
     
-File file = new File(%22/data/data/%22 + potential.substring(start, end) +
+String packageName = potential.substring(start, end);%0A      File dataDir = new File(%22/data/data/%22 + packageName);%0A      if (isWriteableDirectory(dataDir)) %7B%0A        File cacheDir = new File(dataDir,
  %22
-/
 cach
@@ -3805,24 +3805,85 @@
 , %22cache%22);%0A
+        if ((cacheDir.exists()) %7C%7C (cacheDir.mkdir())) %7B%0A    
       if (is
@@ -3901,20 +3901,24 @@
 rectory(
-file
+cacheDir
 )) %7B%0A   
@@ -3918,24 +3918,28 @@
 ) %7B%0A        
+  
+  
 results.add(
@@ -3942,14 +3942,40 @@
 add(
-file);
+cacheDir);%0A          %7D%0A        %7D
 %0A   

Update to r10 of LittleMock.