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

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import de.avm.android.fritzapp.R;
import de.avm.android.fritzapp.util.LocalContacts;
import de.avm.android.fritzapp.util.OnClickCallEmail;
import de.avm.android.fritzapp.util.OnClickCallNumber;
import de.avm.android.tr064.model.Contact;
import de.avm.android.tr064.model.ContactEmail;
import de.avm.android.tr064.model.ContactNumber;
import de.avm.android.tr064.model.IContactable;
import de.usbi.android.util.adapter.ArrayAdapterExt;

/* GUI for a single contact (from the phonebook) */
public class ContactDetailsActivity extends Activity
{
	private TextView mNameView;
	private ListView mListView;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.contactdetails);

		mNameView = (TextView)findViewById(R.id.Name);
		mListView = (ListView)findViewById(R.id.ContactNumbers);
		mListView.setSelector(R.drawable.list_selector_background);
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
	        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
	        {
	            onListItemClick((ListView)parent, view, position, id);
	        }
	    });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    int position, long id)
            {
                return onListItemLongClick((ListView)parent, view, position, id);
            }
        });
		
		if (getIntent().hasExtra(PhoneBookActivity.EXTRA_CONTACT_DATA_KEY))
		{
			setContact((Contact)getIntent().getParcelableExtra(
					PhoneBookActivity.EXTRA_CONTACT_DATA_KEY));
		}
		else if (getIntent().hasExtra(PhoneBookActivity.EXTRA_LOCAL_CONTACT_URI))
		{
			setContact(Uri.parse(getIntent().getStringExtra(
					PhoneBookActivity.EXTRA_LOCAL_CONTACT_URI)));
		}
		else finish(); // nothing to show
	}
	
	/**
	 * Sets content from box' contact
	 * 
	 * @param contact
	 */
	private void setContact(Contact contact)
	{
		mNameView.setText(contact.getRealName());
		ContactablesListAdapter adapter = new ContactablesListAdapter();
		adapter.addAll(contact.getContactNumbers());
		adapter.addAll(contact.getContactEmails());
		mListView.setAdapter(adapter);
	}

	/**
	 * Sets content from local contact
	 * 
	 * @param contactUri
	 */
	private void setContact(Uri contactUri)
	{
		try
		{
			LocalContacts.Contact contact = LocalContacts.getInstance()
					.getContact(this, contactUri);
			if (contact.getName().length() > 0)
				mNameView.setText(contact.getName());
			else
				mNameView.setText(R.string.unknown);
			ContactablesListAdapter adapter = new ContactablesListAdapter();
			adapter.addAll(contact.mAddresses);
			mListView.setAdapter(adapter);
		}
		catch(Exception e)
		{
			finish(); // nothing to show
		}
	}
	
	private void onListItemClick(ListView listView, View view, int position, long id)
    {
		IContactable contactable = (IContactable)listView.getItemAtPosition(position);
    	if (contactable != null)
    	{
    		if (contactable.getClass().equals(ContactEmail.class))
    			new OnClickCallEmail(contactable.getAddress()).onClick(view);
    		else
    			new OnClickCallNumber(contactable.getAddress()).onClick(view);
    	}
    }
    
    private boolean onListItemLongClick(ListView listView, View view, int position, long id)
    {
		IContactable contactable = (IContactable)listView.getItemAtPosition(position);
    	if ((contactable != null) && contactable.getClass().equals(ContactNumber.class))
    	{
    		new OnClickCallNumber(contactable.getAddress()).onLongClick(view);
    		return true;
    	}
    	
    	return false;
    }
	
	public class ContactablesListAdapter extends ArrayAdapterExt<IContactable>
	{
		public ContactablesListAdapter()
		{
		}
		
		public void addAll(Collection<?> addList)
		{
			for (Object entry : addList)
				if (IContactable.class.isAssignableFrom(entry.getClass()))
					super.addEntry((IContactable)entry);
		}
		
		@Override
		public View populateView(final IContactable item, View view, ViewGroup viewGroup)
		{
			// get right layout
			String actionTemplate;
    		if (item.getClass().equals(ContactEmail.class))
    		{
    			if ((view == null) || !ContactEmail.class.equals(view.getTag()))
    			{
    				view = View.inflate(getBaseContext(),
    						R.layout.t_contactemaillistitem, null);
    				view.setTag(item.getClass());
    			}
    			actionTemplate = getResources().getString(R.string.contact_details_emailX);
    		}
    		else
    		{
    			if ((view == null) || !IContactable.class.equals(view.getTag()))
    			{
    				view = View.inflate(getBaseContext(),
    						R.layout.t_contactnumberlistitem, null);
    				view.setTag(IContactable.class);
    			}
    			actionTemplate = getResources().getString(R.string.contact_details_callX);
    		}

    		// set content
			((TextView)view.findViewById(R.id.Action))
					.setText(String.format(actionTemplate,
							item.getTypeDisplay(getBaseContext())));
			((TextView)view.findViewById(R.id.Target))
					.setText(item.getAddressDisplay());

			return view;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		super.onStart();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
	}
}