Show a disambig dialoge to choose a number when initiating a call on a contact.

This fixes 2098966

Change-Id: I6fd80a2fe25ab1b6d36d913cb96c7927939512b7
diff --git a/src/com/android/contacts/ContactsListActivity.java b/src/com/android/contacts/ContactsListActivity.java
index d81e20c..7373ab6 100644
--- a/src/com/android/contacts/ContactsListActivity.java
+++ b/src/com/android/contacts/ContactsListActivity.java
@@ -72,6 +72,7 @@
 import android.provider.ContactsContract.Intents.UI;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
+import android.util.AttributeSet;
 import android.util.Log;
 import android.util.SparseArray;
 import android.view.ContextMenu;
@@ -85,13 +86,18 @@
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.ContextMenu.ContextMenuInfo;
+import android.view.View.OnClickListener;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.AbsListView;
 import android.widget.AdapterView;
 import android.widget.AlphabetIndexer;
 import android.widget.ArrayAdapter;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.CursorAdapter;
 import android.widget.Filter;
 import android.widget.ImageView;
+import android.widget.LinearLayout;
 import android.widget.ListView;
 import android.widget.ResourceCursorAdapter;
 import android.widget.SectionIndexer;
@@ -100,7 +106,9 @@
 
 import java.lang.ref.SoftReference;
 import java.lang.ref.WeakReference;
+import java.util.ArrayList;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Locale;
 
 /*TODO(emillar) I commented most of the code that deals with modes and filtering. It should be
@@ -914,27 +922,13 @@
         menu.add(0, MENU_ITEM_VIEW_CONTACT, 0, R.string.menu_viewContact)
                 .setIntent(new Intent(Intent.ACTION_VIEW, contactUri));
 
-        /*
-        // Calling contact
-        long phoneId = cursor.getLong(PRIMARY_PHONE_ID_COLUMN_INDEX);
-        if (phoneId > 0) {
-            // Get the display label for the number
-            CharSequence label = cursor.getString(PRIMARY_PHONE_LABEL_COLUMN_INDEX);
-            int type = cursor.getInt(PRIMARY_PHONE_TYPE_COLUMN_INDEX);
-            label = ContactsUtils.getDisplayLabel(
-                    this, CommonDataKinds.Phone.CONTENT_ITEM_TYPE, type, label);
-            Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
-                    ContentUris.withAppendedId(Data.CONTENT_URI, id));
+        if (cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0) {
+            // Calling contact
             menu.add(0, MENU_ITEM_CALL, 0,
-                    String.format(getString(R.string.menu_callNumber), label)).setIntent(intent);
-
+                    getString(R.string.menu_call));
             // Send SMS item
-            menu.add(0, MENU_ITEM_SEND_SMS, 0, R.string.menu_sendSMS)
-                    .setIntent(new Intent(Intent.ACTION_SENDTO,
-                            Uri.fromParts("sms",
-                                    cursor.getString(PRIMARY_PHONE_NUMBER_COLUMN_INDEX), null)));
+            menu.add(0, MENU_ITEM_SEND_SMS, 0, getString(R.string.menu_sendSMS));
         }
-         */
 
         // Star toggling
         int starState = cursor.getInt(SUMMARY_STARRED_COLUMN_INDEX);
@@ -972,6 +966,16 @@
                 return true;
             }
 
+            case MENU_ITEM_CALL: {
+                callContact(cursor);
+                return true;
+            }
+
+            case MENU_ITEM_SEND_SMS: {
+                smsContact(cursor);
+                return true;
+            }
+
             case MENU_ITEM_DELETE: {
                 final Uri selectedUri = getContactUri(info.position);
                 doContactDelete(selectedUri);
@@ -1622,33 +1626,86 @@
         ListView list = getListView();
         if (list.hasFocus()) {
             Cursor cursor = (Cursor) list.getSelectedItem();
-            if (cursor != null) {
-                boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0;
-                if (!hasPhone) {
-                    // There is no phone number.
-                    signalError();
-                    return false;
-                }
+            return callContact(cursor);
+        }
+        return false;
+    }
 
-                // TODO: transition to use lookup instead of strong id
-                final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);
-                final String phone = ContactsUtils.querySuperPrimaryPhone(getContentResolver(),
-                        contactId);
-                if (phone == null) {
-                    signalError();
-                    return false;
-                }
+    boolean callContact(Cursor cursor) {
+        return callOrSmsContact(cursor, false /*call*/);
+    }
 
-                Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
-                        Uri.fromParts(Constants.SCHEME_TEL, phone, null));
-                startActivity(intent);
-                return true;
+    boolean smsContact(Cursor cursor) {
+        return callOrSmsContact(cursor, true /*sms*/);
+    }
+
+    /**
+     * Calls the contact which the cursor is point to.
+     * @return true if the call was initiated, false otherwise
+     */
+    boolean callOrSmsContact(Cursor cursor, boolean sendSms) {
+        if (cursor != null) {
+            boolean hasPhone = cursor.getInt(SUMMARY_HAS_PHONE_COLUMN_INDEX) != 0;
+            if (!hasPhone) {
+                // There is no phone number.
+                signalError();
+                return false;
             }
+
+            String phone = null;
+            Cursor phonesCursor = null;
+            phonesCursor = queryPhoneNumbers(cursor.getLong(SUMMARY_ID_COLUMN_INDEX));
+            if (phonesCursor == null || phonesCursor.getCount() == 0) {
+                // No valid number
+                signalError();
+                return false;
+            } else if (phonesCursor.getCount() == 1) {
+                // only one number, call it.
+                phone = phonesCursor.getString(phonesCursor.getColumnIndex(Phone.NUMBER));
+            } else {
+                phonesCursor.moveToPosition(-1);
+                while (phonesCursor.moveToNext()) {
+                    if (phonesCursor.getInt(phonesCursor.
+                            getColumnIndex(Data.IS_SUPER_PRIMARY)) != 0) {
+                        // Found super primary, call it.
+                        phone = phonesCursor.
+                        getString(phonesCursor.getColumnIndex(Phone.NUMBER));
+                        break;
+                    }
+                }
+            }
+
+            if (phone == null) {
+                // Display dialog to choose a number to call.
+                PhoneDisambigDialog phoneDialog = new PhoneDisambigDialog(
+                        this, phonesCursor, sendSms);
+                phoneDialog.show();
+            } else {
+                if (sendSms) {
+                    ContactsUtils.initiateSms(this, phone);
+                } else {
+                    ContactsUtils.initiateCall(this, phone);
+                }
+            }
+            return true;
         }
 
         return false;
     }
 
+    private Cursor queryPhoneNumbers(long contactId) {
+        Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
+        Uri dataUri = Uri.withAppendedPath(baseUri, Contacts.Data.CONTENT_DIRECTORY);
+
+        Cursor c = getContentResolver().query(dataUri,
+                new String[] {Data._ID, Phone.NUMBER, Data.IS_SUPER_PRIMARY},
+                Data.MIMETYPE + "=?", new String[] {Phone.CONTENT_ITEM_TYPE}, null);
+        if (c != null && c.moveToFirst()) {
+            return c;
+        }
+        return null;
+    }
+
     /**
      * Signal an error to the user.
      */
diff --git a/src/com/android/contacts/ContactsUtils.java b/src/com/android/contacts/ContactsUtils.java
index 7537d30..dea0bad 100644
--- a/src/com/android/contacts/ContactsUtils.java
+++ b/src/com/android/contacts/ContactsUtils.java
@@ -353,4 +353,22 @@
         }
         return createTabIndicatorView(parent, null, icon);
     }
+
+    /**
+     * Kick off an intent to initiate a call.
+     */
+    public static void initiateCall(Context context, CharSequence phoneNumber) {
+        Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
+                Uri.fromParts("tel", phoneNumber.toString(), null));
+        context.startActivity(intent);
+    }
+
+    /**
+     * Kick off an intent to initiate an Sms/Mms message.
+     */
+    public static void initiateSms(Context context, CharSequence phoneNumber) {
+        Intent intent = new Intent(Intent.ACTION_SENDTO,
+                Uri.fromParts("sms", phoneNumber.toString(), null));
+        context.startActivity(intent);
+    }
 }
diff --git a/src/com/android/contacts/PhoneDisambigDialog.java b/src/com/android/contacts/PhoneDisambigDialog.java
new file mode 100644
index 0000000..58d3721
--- /dev/null
+++ b/src/com/android/contacts/PhoneDisambigDialog.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.contacts;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+
+import android.app.AlertDialog;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.database.Cursor;
+import android.provider.ContactsContract.Data;
+import android.provider.ContactsContract.CommonDataKinds.Phone;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.SimpleCursorAdapter;
+
+/**
+ * Class used for displaying a dialog with a list of phone numbers of which
+ * one will be chosen to make a call or initiate an sms message.
+ */
+public class PhoneDisambigDialog implements DialogInterface.OnClickListener,
+        DialogInterface.OnDismissListener, CompoundButton.OnCheckedChangeListener{
+
+    private boolean mMakePrimary = false;
+    private Context mContext;
+    private AlertDialog mDialog;
+    private boolean mSendSms;
+    private Cursor mPhonesCursor;
+
+    public PhoneDisambigDialog(Context context, Cursor phonesCursor) {
+        this(context, phonesCursor, false /*make call*/);
+    }
+
+    public PhoneDisambigDialog(Context context, Cursor phonesCursor, boolean sendSms) {
+        mContext = context;
+        mSendSms = sendSms;
+        mPhonesCursor = phonesCursor;
+
+        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+        View setPrimaryView = inflater.
+                inflate(R.layout.set_primary_checkbox, null);
+        ((CheckBox) setPrimaryView.findViewById(R.id.setPrimary)).
+                setOnCheckedChangeListener(this);
+
+        // Need to show disambig dialogue.
+        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext).
+            setCursor(mPhonesCursor, this, Phone.NUMBER).
+                    setTitle(sendSms ? R.string.sms_disambig_title : R.string.call_disambig_title).
+                    setView(setPrimaryView);
+
+        mDialog = dialogBuilder.create();
+    }
+
+    /**
+     * Show the dialog.
+     */
+    public void show() {
+        mDialog.show();
+    }
+
+    public void onClick(DialogInterface dialog, int which) {
+        if (mPhonesCursor.moveToPosition(which)) {
+            long id = mPhonesCursor.getLong(mPhonesCursor.getColumnIndex(Data._ID));
+            String phone = mPhonesCursor.getString(mPhonesCursor.getColumnIndex(Phone.NUMBER));
+            if (mMakePrimary) {
+                ContentValues values = new ContentValues(1);
+                values.put(Data.IS_SUPER_PRIMARY, 1);
+                mContext.getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, id),
+                        values, null, null);
+            }
+
+            if (mSendSms) {
+                ContactsUtils.initiateSms(mContext, phone);
+            } else {
+                ContactsUtils.initiateCall(mContext, phone);
+            }
+        } else {
+            dialog.dismiss();
+        }
+    }
+
+    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+        mMakePrimary = isChecked;
+    }
+
+    public void onDismiss(DialogInterface dialog) {
+        mPhonesCursor.close();
+    }
+}
diff --git a/src/com/android/contacts/ViewContactActivity.java b/src/com/android/contacts/ViewContactActivity.java
index ddd0abb..d2328ee 100644
--- a/src/com/android/contacts/ViewContactActivity.java
+++ b/src/com/android/contacts/ViewContactActivity.java
@@ -614,17 +614,7 @@
         }
 
         // Update the primary values in the data record.
-        ContentValues values = new ContentValues(2);
-        values.put(Data.IS_PRIMARY, 1);
-
-        if (entry.ids.size() > 0) {
-            for (int i = 0; i < entry.ids.size(); i++) {
-                getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI,
-                        entry.ids.get(i)),
-                        values, null, null);
-            }
-        }
-
+        ContentValues values = new ContentValues(1);
         values.put(Data.IS_SUPER_PRIMARY, 1);
         getContentResolver().update(ContentUris.withAppendedId(Data.CONTENT_URI, entry.id),
                 values, null, null);