/* 
 * 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.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;
import de.avm.android.fritzapp.R;
import de.avm.android.fritzapp.com.ConnectionProblem;
import de.avm.android.fritzapp.gui.Help;

/* HelperCalss for access of ressources (strings etc) */
public class ResourceHelper
{
	private static final String TAG = "ResourceHelper";
	
	// append this to android:versionName in app's manifest
	// to tag it as lab version
	public final static String LAB_TAG = "lab";
	private static Boolean mIsLabBuild = null;
	
	/**
	 * Gets the icon for an activity class. (launcher icon)
	 * 
	 * @param clazz
	 *            the class
	 * @param c
	 *            a valid context
	 * 
	 * @return the icon for class
	 */
	public static Drawable getIconForClass(Class<?> clazz, boolean launcherIcon,
			Context c)
	{
		int id = getIdentifierOfTyp(
				(launcherIcon) ? "_metaicon" : "_icon", "drawable", clazz, c);
		if (id != 0) {
			return c.getResources().getDrawable(id);
		} else {
			return c.getResources().getDrawable((launcherIcon) ?
					R.drawable.features_metaicon : R.drawable.features_icon);
		}
	}

	/**
	 * Gets the label for an activityclass. (launchertext)
	 * 
	 * @param clazz
	 *            the clazz
	 * @param c
	 *            a valid context
	 * 
	 * @return the label for class
	 */
	public static String getLabelForClass(Class<?> clazz, Context c) {
		int id = getIdentifierOfTyp("_label", "string", clazz, c);
		if (id != 0) {
			return c.getResources().getString(id);
		} else {
			return "MISSING LABEL";
		}
	}

	/**
	 * Gets the text for a connection problem.
	 * 
	 * @param problem
	 *            the problem
	 * @param context
	 *            a valid context
	 * 
	 * @return the text for connection problem
	 */
	public static String getTextForConnectionProblem(ConnectionProblem problem,
			Context context)
	{
		int id = context.getResources().getIdentifier(
				"problem_" + problem.toString().toLowerCase(Locale.US), "string", 
				context.getApplicationContext().getPackageName()); 
		return (id == 0) ? "CONNECTION_PROBLEM" : context.getResources().getString(id);
	}

	/**
	 * Gets the identifier of a specific type for a class.
	 * 
	 * @param type
	 *            the type
	 * @param resTyp
	 *            the res typ 
	 * @param clazz
	 *            the clazz
	 * @param c
	 *            a valid context
	 * 
	 * @return the identifier of typ
	 */
	protected static int getIdentifierOfTyp(String type, String resTyp,
			Class<?> clazz, Context c) {
		String idName = clazz.getSimpleName().replace("Activity", "");
		idName = idName.toLowerCase(Locale.US) + type;
		int id = c.getResources().getIdentifier(idName, resTyp,
				c.getApplicationContext().getPackageName());
		return id;
	}
	
	/**
	 * Gets the Text for a help topic
	 * 
	 * @param topic
	 * 			help topic
	 * @param c
	 *            a valid context
	 * @return the text
	 */
	public static String getTextForHelpTopic(Help.HelpTopic topic, Context c)
	{
		int id = c.getResources().getIdentifier(
				"help_" + topic.toString().toLowerCase(Locale.US), "string",
				c.getApplicationContext().getPackageName());
		if (id == 0) id = R.string.help_general; // default on error

		return c.getResources().getString(id);
	}

	public static String getVersion(Context context)
	{
		if (context != null)
		{
			Context appContext = context.getApplicationContext();
			try
			{
				return appContext.getPackageManager()
					   .getPackageInfo(appContext.getPackageName(), 0)
					   .versionName;
			}
			catch(NameNotFoundException exp)
			{
			}
			return appContext.getString(R.string.unknown);
		}

		return "";
	}

	public static boolean isLabBuild(Context context)
	{
		if ((mIsLabBuild == null) && (context != null)) 
		{
			Context appContext = context.getApplicationContext();
			try
			{
				String version = appContext.getPackageManager()
					   .getPackageInfo(appContext.getPackageName(), 0)
					   .versionName;
				mIsLabBuild = Boolean.valueOf((TextUtils.isEmpty(version)) ?
						false : version.toLowerCase(Locale.US).contains(LAB_TAG));
			}
			catch(NameNotFoundException exp)
			{
			}
		}
		return (mIsLabBuild != null) && mIsLabBuild;
	}

	public static String getApplicationName(Context context)
	{
		return context.getString((isLabBuild(context)) ?
				R.string.app_name_lab : R.string.app_name);
	}
	
	/**
	 * Sets alternative title symbol if needed
	 * 
	 * @param activity
	 *			the activity using t_titlebar
	 */
	public static void setAltTitleSymbol(Activity activity)
	{
		if (isLabBuild(activity))
		{
			ImageView icon = (ImageView)activity.findViewById(R.id.fritzIcon);
			if (icon != null)
				icon.setImageResource(R.drawable.fritzapp_icon_lab);
		}
	}

	/**
	 * Sets title in included framework layout
	 * The activity layout must include
	 * <p>
	 *			&lt;include android:id="@+id/title_text" layout="@android:layout/preference_category" /&gt;
	 * <p>
	 *			&lt;ViewStub android:id="@+id/fallback_title_text" android:layout="@layout/preference_category" /&gt;
	 * 
	 * @param activity
	 *			the activity
	 * @param resId
	 * 			the title string resource
	 */
	public static TextView setTitle(Activity activity, int resId)
	{
		try
		{
			View includeView = activity.findViewById(R.id.title_text);
			if (includeView != null)
			{
				if (TextView.class.equals(includeView.getClass()))
				{
					// original framework's preference_category is TextView
					if (resId != 0)
					{
						includeView.setVisibility(View.VISIBLE);
						((TextView)includeView).setText(resId);
					}
					else includeView.setVisibility(View.GONE);
					return (TextView)includeView;
				}
				else
				{
					View view = includeView.findViewById(android.R.id.title);
					if (TextView.class.equals(view.getClass()))
					{
						// replacements of preference_category might be more complex
						if (resId != 0)
						{
							includeView.setVisibility(View.VISIBLE);
							((TextView)view).setText(resId);
						}
						else includeView.setVisibility(View.GONE);
						return (TextView)view;
					}
				}
				
				// failed to find title text view
				includeView.setVisibility(View.GONE);
			}
			
			// load our own layout (original framework's preference_category)
			// on resId==0 load it too, because this method could be called again an
			// same activity
			includeView = ((ViewStub)activity.findViewById(R.id.fallback_title_text))
					.inflate();
			if (includeView != null)
			{
				if (resId == 0)
					includeView.setVisibility(View.GONE);
				else
					((TextView)includeView).setText(resId);
			}
			return (TextView)includeView;
		}
		catch(Exception e)
		{
			Log.e((activity == null) ? TAG : activity.getClass().getSimpleName(),
					"Cannot set title text.");
			e.printStackTrace();
		}
		return null;
	}
}
