Merge "First pass on consolidating usage of AccountManager (1/2)"
diff --git a/src/com/android/contacts/common/model/AccountTypeManager.java b/src/com/android/contacts/common/model/AccountTypeManager.java
index 0b12305..705f5bf 100644
--- a/src/com/android/contacts/common/model/AccountTypeManager.java
+++ b/src/com/android/contacts/common/model/AccountTypeManager.java
@@ -25,6 +25,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.SharedPreferences;
 import android.content.SyncAdapterType;
 import android.content.SyncStatusObserver;
 import android.content.pm.PackageManager;
@@ -43,6 +44,7 @@
 import android.util.Log;
 import android.util.TimingLogger;
 
+import com.android.contacts.R;
 import com.android.contacts.common.MoreContactUtils;
 import com.android.contacts.common.list.ContactListFilterController;
 import com.android.contacts.common.model.account.AccountType;
@@ -131,6 +133,11 @@
         }
 
         @Override
+        public Account getDefaultGoogleAccount() {
+            return null;
+        }
+
+        @Override
         public List<AccountWithDataSet> getSortedAccounts(AccountWithDataSet defaultAccount,
                 boolean contactWritableOnly) {
             return Collections.emptyList();
@@ -167,6 +174,39 @@
      */
     public abstract List<AccountWithDataSet> getGroupWritableAccounts();
 
+    /**
+     * Returns the default google account.
+     */
+    public abstract Account getDefaultGoogleAccount();
+
+    static Account getDefaultGoogleAccount(AccountManager accountManager,
+            SharedPreferences prefs, String defaultAccountKey) {
+        // Get all the google accounts on the device
+        final Account[] accounts = accountManager.getAccountsByType(
+                GoogleAccountType.ACCOUNT_TYPE);
+        if (accounts == null || accounts.length == 0) {
+            return null;
+        }
+
+        // Get the default account from preferences
+        final String defaultAccount = prefs.getString(defaultAccountKey, null);
+        final AccountWithDataSet accountWithDataSet = defaultAccount == null ? null :
+                AccountWithDataSet.unstringify(defaultAccount);
+
+        // Look for an account matching the one from preferences
+        if (accountWithDataSet != null) {
+            for (int i = 0; i < accounts.length; i++) {
+                if (TextUtils.equals(accountWithDataSet.name, accounts[i].name)
+                        && TextUtils.equals(accountWithDataSet.type, accounts[i].type)) {
+                    return accounts[i];
+                }
+            }
+        }
+
+        // Just return the first one
+        return accounts[0];
+    }
+
     public abstract AccountType getAccountType(AccountTypeWithDataSet accountTypeWithDataSet);
 
     public final AccountType getAccountType(String accountType, String dataSet) {
@@ -739,6 +779,20 @@
     }
 
     /**
+     * Returns the default google account specified in preferences, the first google account
+     * if it is not specified in preferences or is no longer on the device, and null otherwise.
+     */
+    @Override
+    public Account getDefaultGoogleAccount() {
+        final AccountManager accountManager = AccountManager.get(mContext);
+        final SharedPreferences sharedPreferences =
+                mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
+        final String defaultAccountKey =
+                mContext.getResources().getString(R.string.contact_editor_default_account_key);
+        return getDefaultGoogleAccount(accountManager, sharedPreferences, defaultAccountKey);
+    }
+
+    /**
      * Find the best {@link DataKind} matching the requested
      * {@link AccountType#accountType}, {@link AccountType#dataSet}, and {@link DataKind#mimeType}.
      * If no direct match found, we try searching {@link FallbackAccountType}.
diff --git a/tests/src/com/android/contacts/common/model/AccountTypeManagerDefaultAccountTests.java b/tests/src/com/android/contacts/common/model/AccountTypeManagerDefaultAccountTests.java
new file mode 100644
index 0000000..9a3f91b
--- /dev/null
+++ b/tests/src/com/android/contacts/common/model/AccountTypeManagerDefaultAccountTests.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2016 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.common.model;
+
+import android.accounts.Account;
+import android.accounts.AccountManager;
+import android.content.SharedPreferences;
+import android.test.InstrumentationTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import com.android.contacts.common.model.account.AccountWithDataSet;
+import com.android.contacts.common.model.account.GoogleAccountType;
+
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for {@link AccountTypeManager#getDefaultGoogleAccount()}
+ */
+@SmallTest
+public class AccountTypeManagerDefaultAccountTests extends InstrumentationTestCase {
+
+    private static final Account[] ACCOUNTS = new Account[2];
+    static {
+        ACCOUNTS[0] = new Account("name1", GoogleAccountType.ACCOUNT_TYPE);
+        ACCOUNTS[1] = new Account("name2", GoogleAccountType.ACCOUNT_TYPE);
+    }
+
+    @Mock private AccountManager mAccountManager;
+    @Mock private SharedPreferences mPrefs;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        System.setProperty("dexmaker.dexcache",
+                getInstrumentation().getTargetContext().getCacheDir().getPath());
+        MockitoAnnotations.initMocks(this);
+    }
+
+    public void testGetDefaultAccount_NoAccounts() {
+        assertNull(getDefaultGoogleAccountName());
+    }
+
+    public void testGetDefaultAccount_NoAccounts_DefaultPreferenceSet() {
+        when(mPrefs.getString(Mockito.anyString(), Mockito.anyString())).thenReturn(
+                getDefaultAccountPreference("name1", GoogleAccountType.ACCOUNT_TYPE));
+        assertNull(getDefaultGoogleAccountName());
+    }
+
+    public void testGetDefaultAccount_NoDefaultAccountPreferenceSet() {
+        when(mAccountManager.getAccountsByType(Mockito.anyString())).thenReturn(ACCOUNTS);
+        assertEquals("name1", getDefaultGoogleAccountName());
+    }
+
+    public void testGetDefaultAccount_DefaultAccountPreferenceSet() {
+        when(mAccountManager.getAccountsByType(Mockito.anyString())).thenReturn(ACCOUNTS);
+        when(mPrefs.getString(Mockito.anyString(), Mockito.anyString())).thenReturn(
+                getDefaultAccountPreference("name2", GoogleAccountType.ACCOUNT_TYPE));
+        assertEquals("name2", getDefaultGoogleAccountName());
+    }
+
+    public void testGetDefaultAccount_DefaultAccountPreferenceSet_NonGoogleAccountType() {
+        when(mAccountManager.getAccountsByType(Mockito.anyString())).thenReturn(ACCOUNTS);
+        when(mPrefs.getString(Mockito.anyString(), Mockito.anyString())).thenReturn(
+                getDefaultAccountPreference("name3", "type3"));
+        assertEquals("name1", getDefaultGoogleAccountName());
+    }
+
+    public void testGetDefaultAccount_DefaultAccountPreferenceSet_UnknownName() {
+        when(mAccountManager.getAccountsByType(Mockito.anyString())).thenReturn(ACCOUNTS);
+        when(mPrefs.getString(Mockito.anyString(), Mockito.anyString())).thenReturn(
+                getDefaultAccountPreference("name4",GoogleAccountType.ACCOUNT_TYPE));
+        assertEquals("name1", getDefaultGoogleAccountName());
+    }
+
+    private final String getDefaultGoogleAccountName() {
+        // We don't need the real preference key value since it's mocked
+        final Account account = AccountTypeManager.getDefaultGoogleAccount(
+                mAccountManager, mPrefs, "contact_editor_default_account_key");
+        return account == null ? null : account.name;
+    }
+
+    private static final String getDefaultAccountPreference(String name, String type) {
+        return new AccountWithDataSet(name, type, /* dataSet */ null).stringify();
+    }
+}
\ No newline at end of file
diff --git a/tests/src/com/android/contacts/common/test/mocks/MockAccountTypeManager.java b/tests/src/com/android/contacts/common/test/mocks/MockAccountTypeManager.java
index 3ffb607..f4ec238 100644
--- a/tests/src/com/android/contacts/common/test/mocks/MockAccountTypeManager.java
+++ b/tests/src/com/android/contacts/common/test/mocks/MockAccountTypeManager.java
@@ -15,6 +15,8 @@
  */
 package com.android.contacts.common.test.mocks;
 
+import android.accounts.Account;
+
 import com.android.contacts.common.model.AccountTypeManager;
 import com.android.contacts.common.model.account.AccountType;
 import com.android.contacts.common.model.account.AccountTypeWithDataSet;
@@ -77,6 +79,11 @@
     }
 
     @Override
+    public Account getDefaultGoogleAccount() {
+        return null;
+    }
+
+    @Override
     public Map<AccountTypeWithDataSet, AccountType> getUsableInvitableAccountTypes() {
         return Maps.newHashMap(); // Always returns empty
     }