Implement the "Delete Profile" button in the AutoFill editor.

Sync a null profile to BrowserSettings and remove the current
profile data from the editor UI and database.

Change-Id: I9ee911640882841b500914be5c381f686bc20e81
diff --git a/res/values/strings.xml b/res/values/strings.xml
index e5adc93..7d7fd0f 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -392,6 +392,8 @@
     <string name="autofill_profile_editor_save_profile">Save profile</string>
     <!-- Toast message displayed when the profile has been successfully saved [CHAR-LIMIT=none] -->
     <string name="autofill_profile_successful_save">Profile saved</string>
+    <!-- Toast message displayed when the profile has been successfully deleted [CHAR-LIMIT=none] -->
+    <string name="autofill_profile_successful_delete">Profile deleted</string>
     <!-- Button text to delete all the AutoFill profile data [CHAR-LIMIT=20] -->
     <string name="autofill_profile_editor_delete_profile">Delete profile data</string>
 
diff --git a/src/com/android/browser/AutoFillProfileDatabase.java b/src/com/android/browser/AutoFillProfileDatabase.java
index 0204d7e..3345e92 100644
--- a/src/com/android/browser/AutoFillProfileDatabase.java
+++ b/src/com/android/browser/AutoFillProfileDatabase.java
@@ -142,6 +142,12 @@
                 null, null, null, "1");
     }
 
+    public void dropProfile(int id) {
+        final String sql = "DELETE FROM " + PROFILES_TABLE_NAME +" WHERE " + Profiles._ID + " = ?;";
+        final Object[] params = { id };
+        getDatabase(true).execSQL(sql, params);
+    }
+
     public void close() {
         mOpenHelper.close();
     }
diff --git a/src/com/android/browser/AutoFillSettingsFragment.java b/src/com/android/browser/AutoFillSettingsFragment.java
index 7728149..06a4256 100644
--- a/src/com/android/browser/AutoFillSettingsFragment.java
+++ b/src/com/android/browser/AutoFillSettingsFragment.java
@@ -18,6 +18,8 @@
 
 import android.app.Fragment;
 import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
@@ -43,13 +45,34 @@
     private EditText mCountryEdit;
     private EditText mPhoneEdit;
 
+    // Used to display toast after DB interactions complete.
+    private Handler mHandler;
+
+    private final static int PROFILE_SAVED_MSG = 100;
+    private final static int PROFILE_DELETED_MSG = 101;
+
     // For now we support just one profile so it's safe to hardcode the
     // id to 1 here. In the future this unique identifier will be set
     // dynamically.
     private int mUniqueId = 1;
 
     public AutoFillSettingsFragment() {
+        mHandler = new Handler() {
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                case PROFILE_SAVED_MSG:
+                    Toast.makeText(getActivity(), R.string.autofill_profile_successful_save,
+                            Toast.LENGTH_SHORT).show();
+                    break;
 
+                case PROFILE_DELETED_MSG:
+                    Toast.makeText(getActivity(), R.string.autofill_profile_successful_delete,
+                            Toast.LENGTH_SHORT).show();
+                    break;
+                }
+            }
+        };
     }
 
     @Override
@@ -78,26 +101,43 @@
         Button saveButton = (Button)v.findViewById(R.id.autofill_profile_editor_save_button);
         saveButton.setOnClickListener(new OnClickListener() {
             public void onClick(View button) {
-                BrowserSettings.getInstance().setAutoFillProfile(getActivity(),
-                        new AutoFillProfile(
-                                mUniqueId,
-                                mFullNameEdit.getText().toString(),
-                                mEmailEdit.getText().toString(),
-                                mCompanyEdit.getText().toString(),
-                                mAddressLine1Edit.getText().toString(),
-                                mAddressLine2Edit.getText().toString(),
-                                mCityEdit.getText().toString(),
-                                mStateEdit.getText().toString(),
-                                mZipEdit.getText().toString(),
-                                mCountryEdit.getText().toString(),
-                                mPhoneEdit.getText().toString()));
+                AutoFillProfile newProfile = new AutoFillProfile(
+                        mUniqueId,
+                        mFullNameEdit.getText().toString(),
+                        mEmailEdit.getText().toString(),
+                        mCompanyEdit.getText().toString(),
+                        mAddressLine1Edit.getText().toString(),
+                        mAddressLine2Edit.getText().toString(),
+                        mCityEdit.getText().toString(),
+                        mStateEdit.getText().toString(),
+                        mZipEdit.getText().toString(),
+                        mCountryEdit.getText().toString(),
+                        mPhoneEdit.getText().toString());
+
+                BrowserSettings.getInstance().setAutoFillProfile(getActivity(), newProfile,
+                        mHandler.obtainMessage(PROFILE_SAVED_MSG));
             }
         });
 
         Button deleteButton = (Button)v.findViewById(R.id.autofill_profile_editor_delete_button);
         deleteButton.setOnClickListener(new OnClickListener() {
             public void onClick(View button) {
-                Toast.makeText(getActivity(), "TODO: Implement me", Toast.LENGTH_SHORT).show();
+                // Clear the UI.
+                mFullNameEdit.setText("");
+                mEmailEdit.setText("");
+                mCompanyEdit.setText("");
+                mAddressLine1Edit.setText("");
+                mAddressLine2Edit.setText("");
+                mCityEdit.setText("");
+                mStateEdit.setText("");
+                mZipEdit.setText("");
+                mCountryEdit.setText("");
+                mPhoneEdit.setText("");
+
+                // Update browser settings and native with a null profile. This will
+                // trigger the current profile to get deleted from the DB.
+                BrowserSettings.getInstance().setAutoFillProfile(getActivity(), null,
+                        mHandler.obtainMessage(PROFILE_DELETED_MSG));
             }
         });
 
diff --git a/src/com/android/browser/BrowserSettings.java b/src/com/android/browser/BrowserSettings.java
index 20b6003..db0f73e 100644
--- a/src/com/android/browser/BrowserSettings.java
+++ b/src/com/android/browser/BrowserSettings.java
@@ -32,6 +32,7 @@
 import android.net.Uri;
 import android.os.AsyncTask;
 import android.os.Handler;
+import android.os.Message;
 import android.preference.PreferenceActivity;
 import android.preference.PreferenceManager;
 import android.preference.PreferenceScreen;
@@ -132,12 +133,13 @@
     private static int pageCacheCapacity;
 
 
-    private AutoFillProfile mAutoFillProfile;
+    private AutoFillProfile autoFillProfile;
     // Default to zero. In the case no profile is set up, the initial
     // value will come from the AutoFillSettingsFragment when the user
     // creates a profile. Otherwise, we'll read the ID of the last used
     // profile from the prefs db.
     private int autoFillActiveProfileId;
+    private static final int NO_AUTOFILL_PROFILE_SET = 0;
 
     // Preference keys that are used outside this class
     public final static String PREF_CLEAR_CACHE = "privacy_clear_cache";
@@ -269,7 +271,7 @@
             s.setGeolocationDatabasePath(b.geolocationDatabasePath);
 
             // Active AutoFill profile data.
-            s.setAutoFillProfile(b.mAutoFillProfile);
+            s.setAutoFillProfile(b.autoFillProfile);
 
             b.updateTabControlSettings();
         }
@@ -349,7 +351,7 @@
                     AutoFillProfileDatabase.Profiles.COUNTRY));
             String phone = c.getString(c.getColumnIndex(
                     AutoFillProfileDatabase.Profiles.PHONE_NUMBER));
-            mAutoFillProfile = new AutoFillProfile(autoFillActiveProfileId,
+            autoFillProfile = new AutoFillProfile(autoFillActiveProfileId,
                     fullName, email, company, addressLine1, addressLine2, city,
                     state, zip, country, phone);
         }
@@ -533,16 +535,21 @@
         update();
     }
 
-    public void setAutoFillProfile(Context ctx, AutoFillProfile profile) {
-        mAutoFillProfile = profile;
-        setActiveAutoFillProfileId(ctx, profile.getUniqueId());
-        // Update the AutoFill DB
-        new SaveProfileToDbTask(ctx).execute(mAutoFillProfile);
-
+    public void setAutoFillProfile(Context ctx, AutoFillProfile profile, Message msg) {
+        if (profile != null) {
+            setActiveAutoFillProfileId(ctx, profile.getUniqueId());
+            // Update the AutoFill DB with the new profile.
+            new SaveProfileToDbTask(ctx, msg).execute(profile);
+        } else {
+            // Delete the current profile.
+            new DeleteProfileFromDbTask(ctx, msg).execute(autoFillProfile.getUniqueId());
+            setActiveAutoFillProfileId(ctx, NO_AUTOFILL_PROFILE_SET);
+        }
+        autoFillProfile = profile;
     }
 
     public AutoFillProfile getAutoFillProfile() {
-        return mAutoFillProfile;
+        return autoFillProfile;
     }
 
     private void setActiveAutoFillProfileId(Context context, int activeProfileId) {
@@ -676,6 +683,7 @@
         setHomePage(ctx, getFactoryResetHomeUrl(ctx));
         // reset appcache max size
         appCacheMaxSize = webStorageSizeManager.getAppCacheMaxSize();
+        setActiveAutoFillProfileId(ctx, NO_AUTOFILL_PROFILE_SET);
     }
 
     /*package*/ static String getFactoryResetHomeUrl(Context context) {
@@ -705,8 +713,6 @@
         rememberPasswords = true;
         saveFormData = true;
         autoFillEnabled = false;
-        // TODO: Should remove the autofill profile fully and
-        // set the active profile id to 0.
         openInBackground = false;
         autoFitPage = true;
         landscapeOnly = false;
@@ -720,27 +726,52 @@
         workersEnabled = true;  // only affects V8. JSC does not have a similar setting
     }
 
-    private class SaveProfileToDbTask extends AsyncTask<AutoFillProfile, Void, Void> {
-
+    private abstract class AutoFillProfileDbTask<T> extends AsyncTask<T, Void, Void> {
         Context mContext;
         AutoFillProfileDatabase mAutoFillProfileDb;
+        Message mCompleteMessage;
 
-        public SaveProfileToDbTask(Context ctx) {
+        public AutoFillProfileDbTask(Context ctx, Message msg) {
             mContext = ctx;
+            mCompleteMessage = msg;
+        }
+
+        protected void onPostExecute(Void result) {
+            if (mCompleteMessage != null) {
+                mCompleteMessage.sendToTarget();
+            }
+            mAutoFillProfileDb.close();
+        }
+
+        abstract protected Void doInBackground(T... values);
+    }
+
+
+    private class SaveProfileToDbTask extends AutoFillProfileDbTask<AutoFillProfile> {
+        public SaveProfileToDbTask(Context ctx, Message msg) {
+            super(ctx, msg);
         }
 
         protected Void doInBackground(AutoFillProfile... values) {
             mAutoFillProfileDb = AutoFillProfileDatabase.getInstance(mContext);
-            assert autoFillActiveProfileId > 0;
-            mAutoFillProfileDb.addOrUpdateProfile(autoFillActiveProfileId, values[0]);
+            assert autoFillActiveProfileId != NO_AUTOFILL_PROFILE_SET;
+            AutoFillProfile newProfile = values[0];
+            mAutoFillProfileDb.addOrUpdateProfile(autoFillActiveProfileId, newProfile);
             return null;
         }
-
-        protected void onPostExecute(Void result) {
-            Toast.makeText(mContext, R.string.autofill_profile_successful_save,
-                    Toast.LENGTH_SHORT).show();
-            mAutoFillProfileDb.close();
-        }
     }
 
+    private class DeleteProfileFromDbTask extends AutoFillProfileDbTask<Integer> {
+        public DeleteProfileFromDbTask(Context ctx, Message msg) {
+            super(ctx, msg);
+        }
+
+        protected Void doInBackground(Integer... values) {
+            mAutoFillProfileDb = AutoFillProfileDatabase.getInstance(mContext);
+            int id = values[0];
+            assert  id > 0;
+            mAutoFillProfileDb.dropProfile(id);
+            return null;
+        }
+    }
 }