/**
   * Set the policy for an account atomically; this also removes any other policy associated with
   * the account and sets the policy key for the account. If policy is null, the policyKey is set to
   * 0 and the securitySyncKey to null. Also, update the account object to reflect the current
   * policyKey and securitySyncKey
   *
   * @param context the caller's context
   * @param account the account whose policy is to be set
   * @param policy the policy to set, or null if we're clearing the policy
   * @param securitySyncKey the security sync key for this account (ignored if policy is null)
   */
  public static void setAccountPolicy(
      Context context, Account account, Policy policy, String securitySyncKey) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    // Make sure this is a valid policy set
    if (policy != null) {
      policy.normalize();
      // Add the new policy (no account will yet reference this)
      ops.add(
          ContentProviderOperation.newInsert(Policy.CONTENT_URI)
              .withValues(policy.toContentValues())
              .build());
      // Make the policyKey of the account our newly created policy, and set the sync key
      ops.add(
          ContentProviderOperation.newUpdate(
                  ContentUris.withAppendedId(Account.CONTENT_URI, account.mId))
              .withValueBackReference(AccountColumns.POLICY_KEY, 0)
              .withValue(AccountColumns.SECURITY_SYNC_KEY, securitySyncKey)
              .build());
    } else {
      ops.add(
          ContentProviderOperation.newUpdate(
                  ContentUris.withAppendedId(Account.CONTENT_URI, account.mId))
              .withValue(AccountColumns.SECURITY_SYNC_KEY, null)
              .withValue(AccountColumns.POLICY_KEY, 0)
              .build());
    }

    // Delete the previous policy associated with this account, if any
    if (account.mPolicyKey > 0) {
      ops.add(
          ContentProviderOperation.newDelete(
                  ContentUris.withAppendedId(Policy.CONTENT_URI, account.mPolicyKey))
              .build());
    }

    try {
      context.getContentResolver().applyBatch(EmailContent.AUTHORITY, ops);
      account.refresh(context);
      syncAccount(context, account);
    } catch (RemoteException e) {
      // This is fatal to a remote process
      throw new IllegalStateException("Exception setting account policy.");
    } catch (OperationApplicationException e) {
      // Can't happen; our provider doesn't throw this exception
    }
  }