Make the receive incoming calls option functional.

+disable the Internet call option if the SIP feature is not available.
+register the primary account even if the receive call option is
disabled.

Change-Id: Ie45e7cc195972266bb9fd8b08f17aa281d24b3ba
diff --git a/src/com/android/phone/CallFeaturesSetting.java b/src/com/android/phone/CallFeaturesSetting.java
index 0b0f8b9..e98a2e9 100644
--- a/src/com/android/phone/CallFeaturesSetting.java
+++ b/src/com/android/phone/CallFeaturesSetting.java
@@ -29,6 +29,8 @@
 import android.content.pm.ResolveInfo;
 import android.database.Cursor;
 import android.media.AudioManager;
+import android.net.sip.SipManager;
+import android.net.sip.SipProfile;
 import android.os.AsyncResult;
 import android.os.Bundle;
 import android.os.Handler;
@@ -51,6 +53,8 @@
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneFactory;
 import com.android.internal.telephony.cdma.TtyIntent;
+import com.android.phone.sip.SipSettings;
+import com.android.phone.sip.SipSharedPreferences;
 
 import java.util.Collection;
 import java.util.HashMap;
@@ -160,6 +164,7 @@
     private Phone mPhone;
 
     private AudioManager mAudioManager;
+    private SipManager mSipManager;
 
     private static final int VM_NOCHANGE_ERROR = 400;
     private static final int VM_RESPONSE_ERROR = 500;
@@ -193,6 +198,8 @@
     private ListPreference mButtonSipCallOptions;
     private ListPreference mVoicemailProviders;
     private PreferenceScreen mVoicemailSettings;
+    private SipSharedPreferences mSipSharedPreferences;
+    private String mSipProfilesDir;
 
     private class VoiceMailProvider {
         public VoiceMailProvider(String name, Intent intent) {
@@ -420,14 +427,56 @@
             this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
             return true;
         } else if (preference == mButtonSipReceiveCalls) {
-            Settings.System.putInt(getContentResolver(),
-                    Settings.System.SIP_RECEIVE_CALLS,
-                    (mButtonSipReceiveCalls.isChecked() ? 1 : 0));
+            final boolean enabled = mButtonSipReceiveCalls.isChecked();
+            mSipSharedPreferences.setReceivingCallsEnabled(enabled);
+            new Thread(new Runnable() {
+                public void run() {
+                    handleSipReceiveCallsOption(enabled);
+                }
+            }).start();
             return true;
         }
         return false;
     }
 
+    private void handleSipReceiveCallsOption(boolean enabled) {
+        List<SipProfile> sipProfileList =
+                SipSettings.retrieveSipListFromDirectory(mSipProfilesDir);
+        for (SipProfile p : sipProfileList) {
+            String sipUri = p.getUriString();
+            boolean openFlag = enabled;
+            // open the profile if it is primary or the receive calls option
+            // is enabled.
+            if (!enabled && sipUri.equals(
+                    mSipSharedPreferences.getPrimaryAccount())) {
+                openFlag = true;
+            }
+            p = updateAutoRegistrationFlag(p, enabled);
+            try {
+                mSipManager.close(sipUri);
+                if (openFlag) {
+                    mSipManager.open(p);
+                }
+            } catch (Exception e) {
+                Log.e(LOG_TAG, "register failed", e);
+            }
+        }
+    }
+
+    private SipProfile updateAutoRegistrationFlag(
+            SipProfile p, boolean enabled) {
+        SipProfile newProfile = new SipProfile.Builder(p)
+                .setAutoRegistration(enabled)
+                .build();
+        try {
+            SipSettings.deleteProfile(mSipProfilesDir + p.getProfileName());
+            SipSettings.saveProfile(mSipProfilesDir, newProfile);
+        } catch (Exception e) {
+            Log.e(LOG_TAG, "updateAutoRegistrationFlag error", e);
+        }
+        return newProfile;
+    }
+
     /**
      * Implemented to support onPreferenceChangeListener to look for preference
      * changes.
@@ -1427,13 +1476,19 @@
         mVMProviderSettingsForced = false;
 
         // Add Internet call settings.
-        addPreferencesFromResource(R.xml.sip_settings_category);
-        mButtonSipReceiveCalls = (CheckBoxPreference) findPreference
-                (BUTTON_SIP_RECEIVE_CALLS);
-        mButtonSipCallOptions = (ListPreference) findPreference
-                (BUTTON_SIP_CALL_OPTIONS);
-        mButtonSipCallOptions.setOnPreferenceChangeListener(this);
-        mButtonSipCallOptions.setSummary(mButtonSipCallOptions.getEntry());
+        if (SipManager.isVoipSupported(this)) {
+            mSipManager = SipManager.getInstance(this);
+            mSipProfilesDir = mPhone.getContext().getFilesDir()
+                    .getAbsolutePath() + SipSettings.PROFILES_DIR;
+            mSipSharedPreferences = new SipSharedPreferences(this);
+            addPreferencesFromResource(R.xml.sip_settings_category);
+            mButtonSipReceiveCalls = (CheckBoxPreference) findPreference
+                    (BUTTON_SIP_RECEIVE_CALLS);
+            mButtonSipCallOptions = (ListPreference) findPreference
+                    (BUTTON_SIP_CALL_OPTIONS);
+            mButtonSipCallOptions.setOnPreferenceChangeListener(this);
+            mButtonSipCallOptions.setSummary(mButtonSipCallOptions.getEntry());
+        }
     }
 
     @Override
diff --git a/src/com/android/phone/SipBroadcastReceiver.java b/src/com/android/phone/SipBroadcastReceiver.java
index fc6700a..ab965c3 100644
--- a/src/com/android/phone/SipBroadcastReceiver.java
+++ b/src/com/android/phone/SipBroadcastReceiver.java
@@ -20,6 +20,7 @@
 import com.android.internal.telephony.PhoneFactory;
 import com.android.internal.telephony.sip.SipPhone;
 import com.android.phone.sip.SipSettings;
+import com.android.phone.sip.SipSharedPreferences;
 
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -39,6 +40,7 @@
  */
 public class SipBroadcastReceiver extends BroadcastReceiver {
     private static final String TAG = SipBroadcastReceiver.class.getSimpleName();
+    private SipSharedPreferences mSipSharedPreferences;
 
     @Override
     public void onReceive(Context context, final Intent intent) {
@@ -48,6 +50,7 @@
             Log.v(TAG, "SIP VOIP not supported: " + action);
             return;
         }
+        mSipSharedPreferences = new SipSharedPreferences(context);
 
         if (action.equals(SipManager.SIP_INCOMING_CALL_ACTION)) {
             takeCall(intent);
@@ -102,15 +105,6 @@
 
     private void registerAllProfiles() {
         final Context context = PhoneApp.getInstance();
-        try {
-            if (Settings.System.getInt(context.getContentResolver(),
-                    Settings.System.SIP_RECEIVE_CALLS) == 0) {
-                return;
-            }
-        } catch (SettingNotFoundException e) {
-            Log.e(TAG, "receive_incoming_call option is not set", e);
-        }
-
         new Thread(new Runnable() {
             public void run() {
                 SipManager sipManager = SipManager.getInstance(context);
@@ -120,8 +114,11 @@
                         + SipSettings.PROFILES_DIR);
                 for (SipProfile profile : sipProfileList) {
                     try {
-                        // TODO: change it to check primary account
-                        if (!profile.getAutoRegistration()) continue;
+                        if (!profile.getAutoRegistration() &&
+                                !profile.getUriString().equals(
+                                mSipSharedPreferences.getPrimaryAccount())) {
+                            continue;
+                        }
                         sipManager.open(profile,
                                 SipManager.SIP_INCOMING_CALL_ACTION, null);
                     } catch (SipException e) {
diff --git a/src/com/android/phone/sip/SipSettings.java b/src/com/android/phone/sip/SipSettings.java
index c78537a..86ae889 100644
--- a/src/com/android/phone/sip/SipSettings.java
+++ b/src/com/android/phone/sip/SipSettings.java
@@ -22,7 +22,6 @@
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
-import android.content.SharedPreferences;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.net.sip.SipProfile;
@@ -86,7 +85,7 @@
     private PreferenceGroup mSipListContainer;
     private Map<String, SipPreference> mSipPreferenceMap;
     private List<SipProfile> mSipProfileList;
-    private SharedPreferences.Editor   mSettingsEditor;
+    private SipSharedPreferences mSipSharedPreferences;
     private int mUid = Process.myUid();
 
 
@@ -109,11 +108,19 @@
 
         void updateSummary() {
             int profileUid = mProfile.getCallingUid();
-            Log.v(TAG, "profile uid is " + profileUid);
-            setSummary((profileUid == 0) ?
+            boolean isPrimary = mProfile.getUriString().equals(
+                    mSipSharedPreferences.getPrimaryAccount());
+            Log.v(TAG, "profile uid is " + profileUid +
+                    " isPrimary:" + isPrimary + " Primary:" +
+                    mSipSharedPreferences.getPrimaryAccount());
+            String summary = (profileUid == 0) ?
                     mInactiveString : ((profileUid == mUid) ?
                     mActiveString : getString(R.string.account_summary,
-                    mActiveString, getPackageNameFromUid(profileUid))));
+                    mActiveString, getPackageNameFromUid(profileUid)));
+            if (isPrimary) {
+                summary += " (Primary) ";
+            }
+            setSummary(summary);
         }
         void updateSummary(String msg) {
             updateSummary();
@@ -138,6 +145,7 @@
         super.onCreate(savedInstanceState);
 
         mSipManager = SipManager.getInstance(SipSettings.this);
+        mSipSharedPreferences = new SipSharedPreferences(this);
         mPackageManager = getPackageManager();
         setContentView(R.layout.sip_settings_ui);
         addPreferencesFromResource(R.xml.sip_setting);
@@ -339,11 +347,11 @@
     }
 
     // TODO: Use the Util class in settings.vpn instead
-    private void deleteProfile(String name) {
+    public static void deleteProfile(String name) {
         deleteProfile(new File(name));
     }
 
-    private void deleteProfile(File file) {
+    private static void deleteProfile(File file) {
         if (file.isDirectory()) {
             for (File child : file.listFiles()) deleteProfile(child);
         }
@@ -358,14 +366,19 @@
         unRegisterProfile(p);
     }
 
-    private void saveProfileToStorage(SipProfile p) throws IOException {
-        if (mProfile != null) deleteProfile(mProfile);
-        File f = new File(mProfilesDirectory + p.getProfileName());
+    public static void saveProfile(String profilesDir, SipProfile p)
+            throws IOException {
+        File f = new File(profilesDir + p.getProfileName());
         if (!f.exists()) f.mkdirs();
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                 new File(f, PROFILE_OBJ_FILE)));
         oos.writeObject(p);
         oos.close();
+    }
+
+    private void saveProfileToStorage(SipProfile p) throws IOException {
+        if (mProfile != null) deleteProfile(mProfile);
+        saveProfile(mProfilesDirectory, p);
         mSipProfileList.add(p);
         addPreferenceFor(p);
     }