/* 
 * Copyright 2015 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.gui;

import java.lang.reflect.Method;
import java.util.LinkedList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.avm.android.fritzapp.R;
import de.avm.android.fritzapp.service.BoxServiceConnection;
import de.avm.android.fritzapp.sipua.UserAgent;
import de.avm.android.fritzapp.sipua.ui.Receiver;
import de.avm.android.fritzapp.util.ResourceHelper;
import de.avm.fundamentals.activities.FeedbackActivityOld;
import de.avm.fundamentals.logger.FileLog;

/*
 * Secondary Features GUI
 */
public class FeaturesActivity extends OverflowMenuActivity
{
	private static final String TAG = "FeaturesActivity";
	
	private ListView mListView = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.features);
		
		mListView = (ListView)findViewById(R.id.DashBoard);
		mListView.setSelector(R.drawable.list_selector_background);
		mListView.setOnKeyListener(new OnKeyListener()
		{
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
				{
					View item = mListView.getSelectedView();
					if (item != null)
						return item.performClick();
				}
				return false;
			}
		});
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
	        {
	            onListItemClick((ListView)parent, v, position, id);
	        }
	    });
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		// show in call screen if call is active
		if (Receiver.call_state != UserAgent.UA_STATE_IDLE) Receiver.moveTop();
		if (!mBoxServiceConnection.bindService(getApplicationContext()))
			FileLog.w(TAG, "Failed to bind to BoxService.");
		// fill according to connection status
		mListView.setAdapter(new StartButtonAdapter());
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		mBoxServiceConnection.unbindService();
	}
	
	private BoxServiceConnection mBoxServiceConnection = new BoxServiceConnection()
	{
		public void onComStatusChanged()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					// fill according to connection status
					mListView.setAdapter(new StartButtonAdapter());
				}
			});
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
	    getMenuInflater().inflate(R.menu.features_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.About:
				Help.showAbout(this);
				break;
				
			case R.id.Help:
				Help.showHelp(this);
				break;

            case R.id.action_feedback:
                startActivity(new Intent(this, FeedbackActivityOld.class));
                break;
		}
		return true;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onBackPressed ()
	{
		// if we have been left with HOME button and later on returned
		// using task switcher, we will not get back to main
		// activity from here by defaulted handling!
        startActivity(new Intent(this, FRITZApp.class));
        finish();
	}

    @SuppressWarnings("unchecked")
	private void onListItemClick(ListView listView, View view, int position, long id)
    {
    	StartButtonAdapter adapter = (StartButtonAdapter)listView.getAdapter();
    	if (adapter != null)
    	{
    		Class<? extends Activity> currActivityClass =
    			(Class<? extends Activity>)adapter.getItem(position);
    		if (currActivityClass != null)
    			new OnClickStartActivityIntent(currActivityClass).onClick(view);
    	}
    }

	/**
	 * Adapter fuer Launcherbuttons
	 */
	protected class StartButtonAdapter extends BaseAdapter
	{
		private LinkedList<Class<? extends Activity>> mActivities =
				new LinkedList<Class<? extends Activity>>();

		/**
		 * Instantiates a new start button adapter.
		 */
		public StartButtonAdapter()
		{
			// all
			mActivities.add(OpenWebActivity.class);			
			mActivities.add(WlanTesterActivity.class);
			mActivities.add(LocalContactsExportActivity.class);
			mActivities.add(SettingsActivity.class);
			
			// remove not available ones
			for (int activityItem = mActivities.size() - 1; activityItem >= 0;
					activityItem--)
			{
				// can we ask the activity if it could be shown?
				Class<?>[] ifs = mActivities.get(activityItem).getInterfaces();
				for (int interfaceItem = 0; interfaceItem < ifs.length;
						interfaceItem++)
				{
					if (OfflineActivity.class.equals(ifs[interfaceItem]))
					{
						try
						{
							// ask the activity, remove if the answer is no
							Method method = mActivities.get(activityItem)
									.getMethod("canShow", (Class[])null);
							if (!(Boolean)method.invoke(null, (Object[])null))
								mActivities.remove(activityItem);
						}
						catch(Exception e)
						{
							mActivities.remove(activityItem);
                            FileLog.w(TAG, e.getMessage(), e);
						}
					}
				}
			}
		}

		public int getCount() {
			return mActivities.size();
		}

		public Object getItem(int pos)
		{
			return mActivities.get(pos);
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		/*
		 * baut den View für einen Launcherbutton zusammen
		 */
		public View getView(int position, View convertView, ViewGroup parent)
		{
			RelativeLayout activityLauncher = (convertView == null) ?
					(RelativeLayout) View.inflate(FeaturesActivity.this,
							R.layout.t_launcherlistitem, null) :
					(RelativeLayout)convertView;
			Class<? extends Activity> currActivityClass = mActivities.get(position);
			Drawable icon = ResourceHelper.getIconForClass(currActivityClass, false,
					FeaturesActivity.this);
			String label = ResourceHelper.getLabelForClass(currActivityClass,
					FeaturesActivity.this);
			ImageView launchIcon = (ImageView) activityLauncher
					.findViewById(R.id.launcher_button);
			TextView text = (TextView) activityLauncher
					.findViewById(R.id.launcher_text);
			launchIcon.setImageDrawable(icon);
			text.setText(label, TextView.BufferType.NORMAL);
			
			// disable view, if nothing to invoke
			Class<?>[] ifs = currActivityClass.getInterfaces();
			for (int interfaceItem = 0; interfaceItem < ifs.length;
					interfaceItem++)
			{
				if (OfflineActivity.class.equals(ifs[interfaceItem]))
				{
					try
					{
						// ask the activity, disable if no intent to invoke
						Method method = currActivityClass
								.getMethod("showIntent", new Class[] {Context.class});
						if ((Intent)method.invoke(null,
								new Object[] {activityLauncher.getContext()}) == null)
							activityLauncher.setEnabled(false);
					}
					catch(Exception e)
					{
						activityLauncher.setEnabled(false);
                        FileLog.w(TAG, e.getMessage(), e);
					}
				}
			}

			return activityLauncher;
		}

		public long getItemId(int position) {
			return position;
		}
	}
}