package com.example.providers;

import android.content.ContentUris;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;


public class ContactsActivity extends FragmentActivity {
  private static final int WORKPHONE_LOADER = 0;
  private static final int MOBILEPHONE_LOADER = 1;
  private static final int EMAIL_LOADER = 2;
  private static final String[] phoneColumns = {
      ContactsContract.Data._ID,
      ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
      ContactsContract.CommonDataKinds.Phone.NUMBER,
      ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
      ContactsContract.CommonDataKinds.Phone.TYPE,
  };
  private static final String workphoneWhere = ContactsContract.CommonDataKinds.Phone.TYPE
      + " = " + ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
  private static final String mobilephoneWhere = ContactsContract.CommonDataKinds.Phone.TYPE
      + " = " + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
  private static final String phoneOrderBy = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
  private static final String[] phoneFrom = new String[] {
      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
      ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER
  };

  private static final String[] emailColumns = {
      ContactsContract.Data._ID,
      ContactsContract.CommonDataKinds.Email.CONTACT_ID,
      ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
      ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY,
      ContactsContract.CommonDataKinds.Email.DATA,
      ContactsContract.CommonDataKinds.Email.TYPE,
      ContactsContract.CommonDataKinds.Email.LABEL,

  };
  private static final String emailOrderBy = ContactsContract.CommonDataKinds.Email.LABEL;
  private static final String[] emailFrom = new String[] {
      ContactsContract.CommonDataKinds.Email.DISPLAY_NAME_PRIMARY,
      ContactsContract.CommonDataKinds.Email.DATA
  };

  private static final int[] to = new int[] {
      R.id.contactName, R.id.contactValue
  };
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
      finish();
      return;
    }
    if (savedInstanceState == null) {
      ContactsListFragment contactList = new ContactsListFragment();
      contactList.setArguments(getIntent().getExtras());
      getSupportFragmentManager().beginTransaction()
          .add(android.R.id.content, contactList).commit();
    }
  }

  public static class ContactsListFragment extends ListFragment implements
      LoaderManager.LoaderCallbacks<Cursor> {
    private int listToShow = WORKPHONE_LOADER;
    private SimpleCursorAdapter scaWorkphone;
    private SimpleCursorAdapter scaMobilephone;
    private SimpleCursorAdapter scaEmail;
    private LoaderManager lm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setHasOptionsMenu(true);
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      lm = getLoaderManager();

      scaWorkphone = new SimpleCursorAdapter(getActivity(),
          R.layout.contacts_item, null, phoneFrom, to,
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      scaMobilephone = new SimpleCursorAdapter(getActivity(),
          R.layout.contacts_item, null, phoneFrom, to,
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      scaEmail = new SimpleCursorAdapter(getActivity(),
          R.layout.contacts_item, null, emailFrom, to,
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      lm.initLoader(WORKPHONE_LOADER, null, this);
      lm.initLoader(MOBILEPHONE_LOADER, null, this);
      lm.initLoader(EMAIL_LOADER, null, this);

      switch (listToShow) {
        case WORKPHONE_LOADER:
          this.setListAdapter(scaWorkphone);
          break;
        case MOBILEPHONE_LOADER:
          this.setListAdapter(scaMobilephone);
          break;
        case EMAIL_LOADER:
          this.setListAdapter(scaEmail);
          break;
      }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
      CursorLoader loader = null;
      switch (id) {
        case WORKPHONE_LOADER:
          loader = new CursorLoader(getActivity(),
              ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneColumns,
              workphoneWhere, null, phoneOrderBy);
          break;
        case MOBILEPHONE_LOADER:
          loader = new CursorLoader(getActivity(),
              ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneColumns,
              mobilephoneWhere, null, phoneOrderBy);
          break;
        case EMAIL_LOADER:
          loader = new CursorLoader(getActivity(),
              ContactsContract.CommonDataKinds.Email.CONTENT_URI, emailColumns,
              null, null, emailOrderBy);
          break;
      }
      return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
      switch (loader.getId()) {
        case WORKPHONE_LOADER:
          scaWorkphone.swapCursor(data);
          break;
        case MOBILEPHONE_LOADER:
          scaMobilephone.swapCursor(data);
          break;
        case EMAIL_LOADER:
          scaEmail.swapCursor(data);
          break;
      }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
      switch (loader.getId()) {
        case WORKPHONE_LOADER:
          scaWorkphone.swapCursor(null);
          break;
        case MOBILEPHONE_LOADER:
          scaMobilephone.swapCursor(null);
          break;
        case EMAIL_LOADER:
          scaEmail.swapCursor(null);
          break;
      }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
      inflater.inflate(R.menu.contacts, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      super.onOptionsItemSelected(item);
      switch (item.getItemId()) {
        case R.id.contactWorkPhone:
          listToShow = WORKPHONE_LOADER;
          this.setListAdapter(scaWorkphone);
          break;
        case R.id.contactMobilePhone:
          listToShow = MOBILEPHONE_LOADER;
          this.setListAdapter(scaMobilephone);
          break;
        case R.id.contactEmail:
          listToShow = EMAIL_LOADER;
          this.setListAdapter(scaEmail);
          break;
        default:
          return false;
      }
      return true;
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
      super.onPrepareOptionsMenu(menu);
      switch (listToShow) {
        case WORKPHONE_LOADER:
          menu.findItem(R.id.contactWorkPhone).setVisible(false);
          menu.findItem(R.id.contactMobilePhone).setVisible(true);
          menu.findItem(R.id.contactEmail).setVisible(true);
          break;
        case MOBILEPHONE_LOADER:
          menu.findItem(R.id.contactWorkPhone).setVisible(true);
          menu.findItem(R.id.contactMobilePhone).setVisible(false);
          menu.findItem(R.id.contactEmail).setVisible(true);
          break;
        case EMAIL_LOADER:
          menu.findItem(R.id.contactWorkPhone).setVisible(true);
          menu.findItem(R.id.contactMobilePhone).setVisible(true);
          menu.findItem(R.id.contactEmail).setVisible(false);
          break;
      }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);
      Uri uri;
      String[] columns;
      switch (listToShow) {
        case WORKPHONE_LOADER:
        case MOBILEPHONE_LOADER:
          uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
          columns = phoneColumns;
          break;
        case EMAIL_LOADER:
          uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
          columns = emailColumns;
          break;
        default:
          return;
      }
      uri = ContentUris.withAppendedId(uri, id);
      Cursor c = getActivity().getContentResolver().query(uri, columns, null, null, null);
      if (c.moveToFirst()) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < c.getColumnCount(); i++) {
          builder.append(c.getColumnName(i)).append(": ")
              .append(c.getString(i)).append("\n");
        }
        Toast.makeText(getActivity(), builder.toString(), Toast.LENGTH_LONG).show();
      }
    }

  }
}