/* 
 * Copyright 2012 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.util;

import java.io.File;
import java.lang.reflect.Method;

import android.content.Context;
import android.os.Build;
import android.os.Environment;

/**
 * Helper for Environment related stuff
  * (compatible to SDK version 5/Android 2.0)
*/
public class EnvironmentHelper
{
	private static final String EXTERNAL_FILES_DIR_FMT = "Android/data/%s/files/";
	
	/**
	 * Gets root of apps external files directory
	 * @return directory to use, null if no external media mounted
	 * 		or default path could not be created
	 */
	public static File getExternalFilesDir(Context context)
	{
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
		{
			// use new API
			try
			{
				Method method = context.getClass().getMethod("getExternalFilesDir", 
						new Class[] { String.class });
				File file = (File)method.invoke(context, new Object[] { null });
				return file;
			}
			catch (Exception e)
			{
				throw new IllegalArgumentException(
						"Cannot call method on argument context.", e);
			}
		}
		
		// use old API
		if (context == null)
			throw new IllegalArgumentException("Argument context must not be null");

		String storageState = Environment.getExternalStorageState();
		boolean writeable;
		if (Environment.MEDIA_MOUNTED.equals(storageState))
			writeable = true;
		else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(storageState))
			writeable = false;
		else
			return null; // not mounted

		File file = new File(Environment.getExternalStorageDirectory (),
				String.format(EXTERNAL_FILES_DIR_FMT, context
						.getApplicationContext().getPackageName()));
		try
		{
			if (writeable && !file.exists()) file.mkdirs();
			return (file.exists() && file.isDirectory())? file : null;
		}
		catch (SecurityException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
