1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.contacts.common.model;
18
19import android.content.ContentValues;
20import android.content.Context;
21import android.database.Cursor;
22import android.net.Uri;
23import android.os.Bundle;
24import android.provider.ContactsContract;
25import android.provider.ContactsContract.CommonDataKinds.BaseTypes;
26import android.provider.ContactsContract.CommonDataKinds.Email;
27import android.provider.ContactsContract.CommonDataKinds.Event;
28import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
29import android.provider.ContactsContract.CommonDataKinds.Im;
30import android.provider.ContactsContract.CommonDataKinds.Nickname;
31import android.provider.ContactsContract.CommonDataKinds.Note;
32import android.provider.ContactsContract.CommonDataKinds.Organization;
33import android.provider.ContactsContract.CommonDataKinds.Phone;
34import android.provider.ContactsContract.CommonDataKinds.Photo;
35import android.provider.ContactsContract.CommonDataKinds.Relation;
36import android.provider.ContactsContract.CommonDataKinds.SipAddress;
37import android.provider.ContactsContract.CommonDataKinds.StructuredName;
38import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
39import android.provider.ContactsContract.CommonDataKinds.Website;
40import android.provider.ContactsContract.Data;
41import android.provider.ContactsContract.Intents;
42import android.provider.ContactsContract.Intents.Insert;
43import android.provider.ContactsContract.RawContacts;
44import android.text.TextUtils;
45import android.util.Log;
46import android.util.SparseArray;
47import android.util.SparseIntArray;
48
49import com.android.contacts.common.ContactsUtils;
50import com.android.contacts.common.model.AccountTypeManager;
51import com.android.contacts.common.model.ValuesDelta;
52import com.android.contacts.common.util.CommonDateUtils;
53import com.android.contacts.common.util.DateUtils;
54import com.android.contacts.common.util.NameConverter;
55import com.android.contacts.common.model.account.AccountType;
56import com.android.contacts.common.model.account.AccountType.EditField;
57import com.android.contacts.common.model.account.AccountType.EditType;
58import com.android.contacts.common.model.account.AccountType.EventEditType;
59import com.android.contacts.common.model.account.GoogleAccountType;
60import com.android.contacts.common.model.dataitem.DataKind;
61import com.android.contacts.common.model.dataitem.PhoneDataItem;
62import com.android.contacts.common.model.dataitem.StructuredNameDataItem;
63
64import java.text.ParsePosition;
65import java.util.ArrayList;
66import java.util.Arrays;
67import java.util.Calendar;
68import java.util.Date;
69import java.util.HashSet;
70import java.util.Iterator;
71import java.util.List;
72import java.util.Locale;
73import java.util.Set;
74
75/**
76 * Helper methods for modifying an {@link RawContactDelta}, such as inserting
77 * new rows, or enforcing {@link AccountType}.
78 */
79public class RawContactModifier {
80    private static final String TAG = RawContactModifier.class.getSimpleName();
81
82    /** Set to true in order to view logs on entity operations */
83    private static final boolean DEBUG = false;
84
85    /**
86     * For the given {@link RawContactDelta}, determine if the given
87     * {@link DataKind} could be inserted under specific
88     * {@link AccountType}.
89     */
90    public static boolean canInsert(RawContactDelta state, DataKind kind) {
91        // Insert possible when have valid types and under overall maximum
92        final int visibleCount = state.getMimeEntriesCount(kind.mimeType, true);
93        final boolean validTypes = hasValidTypes(state, kind);
94        final boolean validOverall = (kind.typeOverallMax == -1)
95                || (visibleCount < kind.typeOverallMax);
96        return (validTypes && validOverall);
97    }
98
99    public static boolean hasValidTypes(RawContactDelta state, DataKind kind) {
100        if (RawContactModifier.hasEditTypes(kind)) {
101            return (getValidTypes(state, kind).size() > 0);
102        } else {
103            return true;
104        }
105    }
106
107    /**
108     * Ensure that at least one of the given {@link DataKind} exists in the
109     * given {@link RawContactDelta} state, and try creating one if none exist.
110     * @return The child (either newly created or the first existing one), or null if the
111     *     account doesn't support this {@link DataKind}.
112     */
113    public static ValuesDelta ensureKindExists(
114            RawContactDelta state, AccountType accountType, String mimeType) {
115        final DataKind kind = accountType.getKindForMimetype(mimeType);
116        final boolean hasChild = state.getMimeEntriesCount(mimeType, true) > 0;
117
118        if (kind != null) {
119            if (hasChild) {
120                // Return the first entry.
121                return state.getMimeEntries(mimeType).get(0);
122            } else {
123                // Create child when none exists and valid kind
124                final ValuesDelta child = insertChild(state, kind);
125                if (kind.mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {
126                    child.setFromTemplate(true);
127                }
128                return child;
129            }
130        }
131        return null;
132    }
133
134    /**
135     * For the given {@link RawContactDelta} and {@link DataKind}, return the
136     * list possible {@link EditType} options available based on
137     * {@link AccountType}.
138     */
139    public static ArrayList<EditType> getValidTypes(RawContactDelta state, DataKind kind) {
140        return getValidTypes(state, kind, null, true, null);
141    }
142
143    /**
144     * For the given {@link RawContactDelta} and {@link DataKind}, return the
145     * list possible {@link EditType} options available based on
146     * {@link AccountType}.
147     *
148     * @param forceInclude Always include this {@link EditType} in the returned
149     *            list, even when an otherwise-invalid choice. This is useful
150     *            when showing a dialog that includes the current type.
151     */
152    public static ArrayList<EditType> getValidTypes(RawContactDelta state, DataKind kind,
153            EditType forceInclude) {
154        return getValidTypes(state, kind, forceInclude, true, null);
155    }
156
157    /**
158     * For the given {@link RawContactDelta} and {@link DataKind}, return the
159     * list possible {@link EditType} options available based on
160     * {@link AccountType}.
161     *
162     * @param forceInclude Always include this {@link EditType} in the returned
163     *            list, even when an otherwise-invalid choice. This is useful
164     *            when showing a dialog that includes the current type.
165     * @param includeSecondary If true, include any valid types marked as
166     *            {@link EditType#secondary}.
167     * @param typeCount When provided, will be used for the frequency count of
168     *            each {@link EditType}, otherwise built using
169     *            {@link #getTypeFrequencies(RawContactDelta, DataKind)}.
170     */
171    private static ArrayList<EditType> getValidTypes(RawContactDelta state, DataKind kind,
172            EditType forceInclude, boolean includeSecondary, SparseIntArray typeCount) {
173        final ArrayList<EditType> validTypes = new ArrayList<EditType>();
174
175        // Bail early if no types provided
176        if (!hasEditTypes(kind)) return validTypes;
177
178        if (typeCount == null) {
179            // Build frequency counts if not provided
180            typeCount = getTypeFrequencies(state, kind);
181        }
182
183        // Build list of valid types
184        final int overallCount = typeCount.get(FREQUENCY_TOTAL);
185        for (EditType type : kind.typeList) {
186            final boolean validOverall = (kind.typeOverallMax == -1 ? true
187                    : overallCount < kind.typeOverallMax);
188            final boolean validSpecific = (type.specificMax == -1 ? true : typeCount
189                    .get(type.rawValue) < type.specificMax);
190            final boolean validSecondary = (includeSecondary ? true : !type.secondary);
191            final boolean forcedInclude = type.equals(forceInclude);
192            if (forcedInclude || (validOverall && validSpecific && validSecondary)) {
193                // Type is valid when no limit, under limit, or forced include
194                validTypes.add(type);
195            }
196        }
197
198        return validTypes;
199    }
200
201    private static final int FREQUENCY_TOTAL = Integer.MIN_VALUE;
202
203    /**
204     * Count up the frequency that each {@link EditType} appears in the given
205     * {@link RawContactDelta}. The returned {@link SparseIntArray} maps from
206     * {@link EditType#rawValue} to counts, with the total overall count stored
207     * as {@link #FREQUENCY_TOTAL}.
208     */
209    private static SparseIntArray getTypeFrequencies(RawContactDelta state, DataKind kind) {
210        final SparseIntArray typeCount = new SparseIntArray();
211
212        // Find all entries for this kind, bailing early if none found
213        final List<ValuesDelta> mimeEntries = state.getMimeEntries(kind.mimeType);
214        if (mimeEntries == null) return typeCount;
215
216        int totalCount = 0;
217        for (ValuesDelta entry : mimeEntries) {
218            // Only count visible entries
219            if (!entry.isVisible()) continue;
220            totalCount++;
221
222            final EditType type = getCurrentType(entry, kind);
223            if (type != null) {
224                final int count = typeCount.get(type.rawValue);
225                typeCount.put(type.rawValue, count + 1);
226            }
227        }
228        typeCount.put(FREQUENCY_TOTAL, totalCount);
229        return typeCount;
230    }
231
232    /**
233     * Check if the given {@link DataKind} has multiple types that should be
234     * displayed for users to pick.
235     */
236    public static boolean hasEditTypes(DataKind kind) {
237        return kind.typeList != null && kind.typeList.size() > 0;
238    }
239
240    /**
241     * Find the {@link EditType} that describes the given
242     * {@link ValuesDelta} row, assuming the given {@link DataKind} dictates
243     * the possible types.
244     */
245    public static EditType getCurrentType(ValuesDelta entry, DataKind kind) {
246        final Long rawValue = entry.getAsLong(kind.typeColumn);
247        if (rawValue == null) return null;
248        return getType(kind, rawValue.intValue());
249    }
250
251    /**
252     * Find the {@link EditType} that describes the given {@link ContentValues} row,
253     * assuming the given {@link DataKind} dictates the possible types.
254     */
255    public static EditType getCurrentType(ContentValues entry, DataKind kind) {
256        if (kind.typeColumn == null) return null;
257        final Integer rawValue = entry.getAsInteger(kind.typeColumn);
258        if (rawValue == null) return null;
259        return getType(kind, rawValue);
260    }
261
262    /**
263     * Find the {@link EditType} that describes the given {@link Cursor} row,
264     * assuming the given {@link DataKind} dictates the possible types.
265     */
266    public static EditType getCurrentType(Cursor cursor, DataKind kind) {
267        if (kind.typeColumn == null) return null;
268        final int index = cursor.getColumnIndex(kind.typeColumn);
269        if (index == -1) return null;
270        final int rawValue = cursor.getInt(index);
271        return getType(kind, rawValue);
272    }
273
274    /**
275     * Find the {@link EditType} with the given {@link EditType#rawValue}.
276     */
277    public static EditType getType(DataKind kind, int rawValue) {
278        for (EditType type : kind.typeList) {
279            if (type.rawValue == rawValue) {
280                return type;
281            }
282        }
283        return null;
284    }
285
286    /**
287     * Return the precedence for the the given {@link EditType#rawValue}, where
288     * lower numbers are higher precedence.
289     */
290    public static int getTypePrecedence(DataKind kind, int rawValue) {
291        for (int i = 0; i < kind.typeList.size(); i++) {
292            final EditType type = kind.typeList.get(i);
293            if (type.rawValue == rawValue) {
294                return i;
295            }
296        }
297        return Integer.MAX_VALUE;
298    }
299
300    /**
301     * Find the best {@link EditType} for a potential insert. The "best" is the
302     * first primary type that doesn't already exist. When all valid types
303     * exist, we pick the last valid option.
304     */
305    public static EditType getBestValidType(RawContactDelta state, DataKind kind,
306            boolean includeSecondary, int exactValue) {
307        // Shortcut when no types
308        if (kind == null || kind.typeColumn == null) return null;
309
310        // Find type counts and valid primary types, bail if none
311        final SparseIntArray typeCount = getTypeFrequencies(state, kind);
312        final ArrayList<EditType> validTypes = getValidTypes(state, kind, null, includeSecondary,
313                typeCount);
314        if (validTypes.size() == 0) return null;
315
316        // Keep track of the last valid type
317        final EditType lastType = validTypes.get(validTypes.size() - 1);
318
319        // Remove any types that already exist
320        Iterator<EditType> iterator = validTypes.iterator();
321        while (iterator.hasNext()) {
322            final EditType type = iterator.next();
323            final int count = typeCount.get(type.rawValue);
324
325            if (exactValue == type.rawValue) {
326                // Found exact value match
327                return type;
328            }
329
330            if (count > 0) {
331                // Type already appears, so don't consider
332                iterator.remove();
333            }
334        }
335
336        // Use the best remaining, otherwise the last valid
337        if (validTypes.size() > 0) {
338            return validTypes.get(0);
339        } else {
340            return lastType;
341        }
342    }
343
344    /**
345     * Insert a new child of kind {@link DataKind} into the given
346     * {@link RawContactDelta}. Tries using the best {@link EditType} found using
347     * {@link #getBestValidType(RawContactDelta, DataKind, boolean, int)}.
348     */
349    public static ValuesDelta insertChild(RawContactDelta state, DataKind kind) {
350        // Bail early if invalid kind
351        if (kind == null) return null;
352        // First try finding a valid primary
353        EditType bestType = getBestValidType(state, kind, false, Integer.MIN_VALUE);
354        if (bestType == null) {
355            // No valid primary found, so expand search to secondary
356            bestType = getBestValidType(state, kind, true, Integer.MIN_VALUE);
357        }
358        return insertChild(state, kind, bestType);
359    }
360
361    /**
362     * Insert a new child of kind {@link DataKind} into the given
363     * {@link RawContactDelta}, marked with the given {@link EditType}.
364     */
365    public static ValuesDelta insertChild(RawContactDelta state, DataKind kind, EditType type) {
366        // Bail early if invalid kind
367        if (kind == null) return null;
368        final ContentValues after = new ContentValues();
369
370        // Our parent CONTACT_ID is provided later
371        after.put(Data.MIMETYPE, kind.mimeType);
372
373        // Fill-in with any requested default values
374        if (kind.defaultValues != null) {
375            after.putAll(kind.defaultValues);
376        }
377
378        if (kind.typeColumn != null && type != null) {
379            // Set type, if provided
380            after.put(kind.typeColumn, type.rawValue);
381        }
382
383        final ValuesDelta child = ValuesDelta.fromAfter(after);
384        state.addEntry(child);
385        return child;
386    }
387
388    /**
389     * Processing to trim any empty {@link ValuesDelta} and {@link RawContactDelta}
390     * from the given {@link RawContactDeltaList}, assuming the given {@link AccountTypeManager}
391     * dictates the structure for various fields. This method ignores rows not
392     * described by the {@link AccountType}.
393     */
394    public static void trimEmpty(RawContactDeltaList set, AccountTypeManager accountTypes) {
395        for (RawContactDelta state : set) {
396            ValuesDelta values = state.getValues();
397            final String accountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
398            final String dataSet = values.getAsString(RawContacts.DATA_SET);
399            final AccountType type = accountTypes.getAccountType(accountType, dataSet);
400            trimEmpty(state, type);
401        }
402    }
403
404    public static boolean hasChanges(RawContactDeltaList set, AccountTypeManager accountTypes) {
405        if (set.isMarkedForSplitting() || set.isMarkedForJoining()) {
406            return true;
407        }
408
409        for (RawContactDelta state : set) {
410            ValuesDelta values = state.getValues();
411            final String accountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
412            final String dataSet = values.getAsString(RawContacts.DATA_SET);
413            final AccountType type = accountTypes.getAccountType(accountType, dataSet);
414            if (hasChanges(state, type)) {
415                return true;
416            }
417        }
418        return false;
419    }
420
421    /**
422     * Processing to trim any empty {@link ValuesDelta} rows from the given
423     * {@link RawContactDelta}, assuming the given {@link AccountType} dictates
424     * the structure for various fields. This method ignores rows not described
425     * by the {@link AccountType}.
426     */
427    public static void trimEmpty(RawContactDelta state, AccountType accountType) {
428        boolean hasValues = false;
429
430        // Walk through entries for each well-known kind
431        for (DataKind kind : accountType.getSortedDataKinds()) {
432            final String mimeType = kind.mimeType;
433            final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
434            if (entries == null) continue;
435
436            for (ValuesDelta entry : entries) {
437                // Skip any values that haven't been touched
438                final boolean touched = entry.isInsert() || entry.isUpdate();
439                if (!touched) {
440                    hasValues = true;
441                    continue;
442                }
443
444                // Test and remove this row if empty and it isn't a photo from google
445                final boolean isGoogleAccount = TextUtils.equals(GoogleAccountType.ACCOUNT_TYPE,
446                        state.getValues().getAsString(RawContacts.ACCOUNT_TYPE));
447                final boolean isPhoto = TextUtils.equals(Photo.CONTENT_ITEM_TYPE, kind.mimeType);
448                final boolean isGooglePhoto = isPhoto && isGoogleAccount;
449
450                if (RawContactModifier.isEmpty(entry, kind) && !isGooglePhoto) {
451                    if (DEBUG) {
452                        Log.v(TAG, "Trimming: " + entry.toString());
453                    }
454                    entry.markDeleted();
455                } else if (!entry.isFromTemplate()) {
456                    hasValues = true;
457                }
458            }
459        }
460        if (!hasValues) {
461            // Trim overall entity if no children exist
462            state.markDeleted();
463        }
464    }
465
466    private static boolean hasChanges(RawContactDelta state, AccountType accountType) {
467        for (DataKind kind : accountType.getSortedDataKinds()) {
468            final String mimeType = kind.mimeType;
469            final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
470            if (entries == null) continue;
471
472            for (ValuesDelta entry : entries) {
473                // An empty Insert must be ignored, because it won't save anything (an example
474                // is an empty name that stays empty)
475                final boolean isRealInsert = entry.isInsert() && !isEmpty(entry, kind);
476                if (isRealInsert || entry.isUpdate() || entry.isDelete()) {
477                    return true;
478                }
479            }
480        }
481        return false;
482    }
483
484    /**
485     * Test if the given {@link ValuesDelta} would be considered "empty" in
486     * terms of {@link DataKind#fieldList}.
487     */
488    public static boolean isEmpty(ValuesDelta values, DataKind kind) {
489        if (Photo.CONTENT_ITEM_TYPE.equals(kind.mimeType)) {
490            return values.isInsert() && values.getAsByteArray(Photo.PHOTO) == null;
491        }
492
493        // No defined fields mean this row is always empty
494        if (kind.fieldList == null) return true;
495
496        for (EditField field : kind.fieldList) {
497            // If any field has values, we're not empty
498            final String value = values.getAsString(field.column);
499            if (ContactsUtils.isGraphic(value)) {
500                return false;
501            }
502        }
503
504        return true;
505    }
506
507    /**
508     * Compares corresponding fields in values1 and values2. Only the fields
509     * declared by the DataKind are taken into consideration.
510     */
511    protected static boolean areEqual(ValuesDelta values1, ContentValues values2, DataKind kind) {
512        if (kind.fieldList == null) return false;
513
514        for (EditField field : kind.fieldList) {
515            final String value1 = values1.getAsString(field.column);
516            final String value2 = values2.getAsString(field.column);
517            if (!TextUtils.equals(value1, value2)) {
518                return false;
519            }
520        }
521
522        return true;
523    }
524
525    /**
526     * Parse the given {@link Bundle} into the given {@link RawContactDelta} state,
527     * assuming the extras defined through {@link Intents}.
528     */
529    public static void parseExtras(Context context, AccountType accountType, RawContactDelta state,
530            Bundle extras) {
531        if (extras == null || extras.size() == 0) {
532            // Bail early if no useful data
533            return;
534        }
535
536        parseStructuredNameExtra(context, accountType, state, extras);
537        parseStructuredPostalExtra(accountType, state, extras);
538
539        {
540            // Phone
541            final DataKind kind = accountType.getKindForMimetype(Phone.CONTENT_ITEM_TYPE);
542            parseExtras(state, kind, extras, Insert.PHONE_TYPE, Insert.PHONE, Phone.NUMBER);
543            parseExtras(state, kind, extras, Insert.SECONDARY_PHONE_TYPE, Insert.SECONDARY_PHONE,
544                    Phone.NUMBER);
545            parseExtras(state, kind, extras, Insert.TERTIARY_PHONE_TYPE, Insert.TERTIARY_PHONE,
546                    Phone.NUMBER);
547        }
548
549        {
550            // Email
551            final DataKind kind = accountType.getKindForMimetype(Email.CONTENT_ITEM_TYPE);
552            parseExtras(state, kind, extras, Insert.EMAIL_TYPE, Insert.EMAIL, Email.DATA);
553            parseExtras(state, kind, extras, Insert.SECONDARY_EMAIL_TYPE, Insert.SECONDARY_EMAIL,
554                    Email.DATA);
555            parseExtras(state, kind, extras, Insert.TERTIARY_EMAIL_TYPE, Insert.TERTIARY_EMAIL,
556                    Email.DATA);
557        }
558
559        {
560            // Im
561            final DataKind kind = accountType.getKindForMimetype(Im.CONTENT_ITEM_TYPE);
562            fixupLegacyImType(extras);
563            parseExtras(state, kind, extras, Insert.IM_PROTOCOL, Insert.IM_HANDLE, Im.DATA);
564        }
565
566        // Organization
567        final boolean hasOrg = extras.containsKey(Insert.COMPANY)
568                || extras.containsKey(Insert.JOB_TITLE);
569        final DataKind kindOrg = accountType.getKindForMimetype(Organization.CONTENT_ITEM_TYPE);
570        if (hasOrg && RawContactModifier.canInsert(state, kindOrg)) {
571            final ValuesDelta child = RawContactModifier.insertChild(state, kindOrg);
572
573            final String company = extras.getString(Insert.COMPANY);
574            if (ContactsUtils.isGraphic(company)) {
575                child.put(Organization.COMPANY, company);
576            }
577
578            final String title = extras.getString(Insert.JOB_TITLE);
579            if (ContactsUtils.isGraphic(title)) {
580                child.put(Organization.TITLE, title);
581            }
582        }
583
584        // Notes
585        final boolean hasNotes = extras.containsKey(Insert.NOTES);
586        final DataKind kindNotes = accountType.getKindForMimetype(Note.CONTENT_ITEM_TYPE);
587        if (hasNotes && RawContactModifier.canInsert(state, kindNotes)) {
588            final ValuesDelta child = RawContactModifier.insertChild(state, kindNotes);
589
590            final String notes = extras.getString(Insert.NOTES);
591            if (ContactsUtils.isGraphic(notes)) {
592                child.put(Note.NOTE, notes);
593            }
594        }
595
596        // Arbitrary additional data
597        ArrayList<ContentValues> values = extras.getParcelableArrayList(Insert.DATA);
598        if (values != null) {
599            parseValues(state, accountType, values);
600        }
601    }
602
603    private static void parseStructuredNameExtra(
604            Context context, AccountType accountType, RawContactDelta state, Bundle extras) {
605        // StructuredName
606        RawContactModifier.ensureKindExists(state, accountType, StructuredName.CONTENT_ITEM_TYPE);
607        final ValuesDelta child = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE);
608
609        final String name = extras.getString(Insert.NAME);
610        if (ContactsUtils.isGraphic(name)) {
611            final DataKind kind = accountType.getKindForMimetype(StructuredName.CONTENT_ITEM_TYPE);
612            boolean supportsDisplayName = false;
613            if (kind.fieldList != null) {
614                for (EditField field : kind.fieldList) {
615                    if (StructuredName.DISPLAY_NAME.equals(field.column)) {
616                        supportsDisplayName = true;
617                        break;
618                    }
619                }
620            }
621
622            if (supportsDisplayName) {
623                child.put(StructuredName.DISPLAY_NAME, name);
624            } else {
625                Uri uri = ContactsContract.AUTHORITY_URI.buildUpon()
626                        .appendPath("complete_name")
627                        .appendQueryParameter(StructuredName.DISPLAY_NAME, name)
628                        .build();
629                Cursor cursor = context.getContentResolver().query(uri,
630                        new String[]{
631                                StructuredName.PREFIX,
632                                StructuredName.GIVEN_NAME,
633                                StructuredName.MIDDLE_NAME,
634                                StructuredName.FAMILY_NAME,
635                                StructuredName.SUFFIX,
636                        }, null, null, null);
637
638                if (cursor != null) {
639                    try {
640                        if (cursor.moveToFirst()) {
641                            child.put(StructuredName.PREFIX, cursor.getString(0));
642                            child.put(StructuredName.GIVEN_NAME, cursor.getString(1));
643                            child.put(StructuredName.MIDDLE_NAME, cursor.getString(2));
644                            child.put(StructuredName.FAMILY_NAME, cursor.getString(3));
645                            child.put(StructuredName.SUFFIX, cursor.getString(4));
646                        }
647                    } finally {
648                        cursor.close();
649                    }
650                }
651            }
652        }
653
654        final String phoneticName = extras.getString(Insert.PHONETIC_NAME);
655        if (ContactsUtils.isGraphic(phoneticName)) {
656            child.put(StructuredName.PHONETIC_GIVEN_NAME, phoneticName);
657        }
658    }
659
660    private static void parseStructuredPostalExtra(
661            AccountType accountType, RawContactDelta state, Bundle extras) {
662        // StructuredPostal
663        final DataKind kind = accountType.getKindForMimetype(StructuredPostal.CONTENT_ITEM_TYPE);
664        final ValuesDelta child = parseExtras(state, kind, extras, Insert.POSTAL_TYPE,
665                Insert.POSTAL, StructuredPostal.FORMATTED_ADDRESS);
666        String address = child == null ? null
667                : child.getAsString(StructuredPostal.FORMATTED_ADDRESS);
668        if (!TextUtils.isEmpty(address)) {
669            boolean supportsFormatted = false;
670            if (kind.fieldList != null) {
671                for (EditField field : kind.fieldList) {
672                    if (StructuredPostal.FORMATTED_ADDRESS.equals(field.column)) {
673                        supportsFormatted = true;
674                        break;
675                    }
676                }
677            }
678
679            if (!supportsFormatted) {
680                child.put(StructuredPostal.STREET, address);
681                child.putNull(StructuredPostal.FORMATTED_ADDRESS);
682            }
683        }
684    }
685
686    private static void parseValues(
687            RawContactDelta state, AccountType accountType,
688            ArrayList<ContentValues> dataValueList) {
689        for (ContentValues values : dataValueList) {
690            String mimeType = values.getAsString(Data.MIMETYPE);
691            if (TextUtils.isEmpty(mimeType)) {
692                Log.e(TAG, "Mimetype is required. Ignoring: " + values);
693                continue;
694            }
695
696            // Won't override the contact name
697            if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
698                continue;
699            } else if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) {
700                values.remove(PhoneDataItem.KEY_FORMATTED_PHONE_NUMBER);
701                final Integer type = values.getAsInteger(Phone.TYPE);
702                // If the provided phone number provides a custom phone type but not a label,
703                // replace it with mobile (by default) to avoid the "Enter custom label" from
704                // popping up immediately upon entering the ContactEditorFragment
705                if (type != null && type == Phone.TYPE_CUSTOM &&
706                        TextUtils.isEmpty(values.getAsString(Phone.LABEL))) {
707                    values.put(Phone.TYPE, Phone.TYPE_MOBILE);
708                }
709            }
710
711            DataKind kind = accountType.getKindForMimetype(mimeType);
712            if (kind == null) {
713                Log.e(TAG, "Mimetype not supported for account type "
714                        + accountType.getAccountTypeAndDataSet() + ". Ignoring: " + values);
715                continue;
716            }
717
718            ValuesDelta entry = ValuesDelta.fromAfter(values);
719            if (isEmpty(entry, kind)) {
720                continue;
721            }
722
723            ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
724
725            if ((kind.typeOverallMax != 1) || GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
726                // Check for duplicates
727                boolean addEntry = true;
728                int count = 0;
729                if (entries != null && entries.size() > 0) {
730                    for (ValuesDelta delta : entries) {
731                        if (!delta.isDelete()) {
732                            if (areEqual(delta, values, kind)) {
733                                addEntry = false;
734                                break;
735                            }
736                            count++;
737                        }
738                    }
739                }
740
741                if (kind.typeOverallMax != -1 && count >= kind.typeOverallMax) {
742                    Log.e(TAG, "Mimetype allows at most " + kind.typeOverallMax
743                            + " entries. Ignoring: " + values);
744                    addEntry = false;
745                }
746
747                if (addEntry) {
748                    addEntry = adjustType(entry, entries, kind);
749                }
750
751                if (addEntry) {
752                    state.addEntry(entry);
753                }
754            } else {
755                // Non-list entries should not be overridden
756                boolean addEntry = true;
757                if (entries != null && entries.size() > 0) {
758                    for (ValuesDelta delta : entries) {
759                        if (!delta.isDelete() && !isEmpty(delta, kind)) {
760                            addEntry = false;
761                            break;
762                        }
763                    }
764                    if (addEntry) {
765                        for (ValuesDelta delta : entries) {
766                            delta.markDeleted();
767                        }
768                    }
769                }
770
771                if (addEntry) {
772                    addEntry = adjustType(entry, entries, kind);
773                }
774
775                if (addEntry) {
776                    state.addEntry(entry);
777                } else if (Note.CONTENT_ITEM_TYPE.equals(mimeType)){
778                    // Note is most likely to contain large amounts of text
779                    // that we don't want to drop on the ground.
780                    for (ValuesDelta delta : entries) {
781                        if (!isEmpty(delta, kind)) {
782                            delta.put(Note.NOTE, delta.getAsString(Note.NOTE) + "\n"
783                                    + values.getAsString(Note.NOTE));
784                            break;
785                        }
786                    }
787                } else {
788                    Log.e(TAG, "Will not override mimetype " + mimeType + ". Ignoring: "
789                            + values);
790                }
791            }
792        }
793    }
794
795    /**
796     * Checks if the data kind allows addition of another entry (e.g. Exchange only
797     * supports two "work" phone numbers).  If not, tries to switch to one of the
798     * unused types.  If successful, returns true.
799     */
800    private static boolean adjustType(
801            ValuesDelta entry, ArrayList<ValuesDelta> entries, DataKind kind) {
802        if (kind.typeColumn == null || kind.typeList == null || kind.typeList.size() == 0) {
803            return true;
804        }
805
806        Integer typeInteger = entry.getAsInteger(kind.typeColumn);
807        int type = typeInteger != null ? typeInteger : kind.typeList.get(0).rawValue;
808
809        if (isTypeAllowed(type, entries, kind)) {
810            entry.put(kind.typeColumn, type);
811            return true;
812        }
813
814        // Specified type is not allowed - choose the first available type that is allowed
815        int size = kind.typeList.size();
816        for (int i = 0; i < size; i++) {
817            EditType editType = kind.typeList.get(i);
818            if (isTypeAllowed(editType.rawValue, entries, kind)) {
819                entry.put(kind.typeColumn, editType.rawValue);
820                return true;
821            }
822        }
823
824        return false;
825    }
826
827    /**
828     * Checks if a new entry of the specified type can be added to the raw
829     * contact. For example, Exchange only supports two "work" phone numbers, so
830     * addition of a third would not be allowed.
831     */
832    private static boolean isTypeAllowed(int type, ArrayList<ValuesDelta> entries, DataKind kind) {
833        int max = 0;
834        int size = kind.typeList.size();
835        for (int i = 0; i < size; i++) {
836            EditType editType = kind.typeList.get(i);
837            if (editType.rawValue == type) {
838                max = editType.specificMax;
839                break;
840            }
841        }
842
843        if (max == 0) {
844            // This type is not allowed at all
845            return false;
846        }
847
848        if (max == -1) {
849            // Unlimited instances of this type are allowed
850            return true;
851        }
852
853        return getEntryCountByType(entries, kind.typeColumn, type) < max;
854    }
855
856    /**
857     * Counts occurrences of the specified type in the supplied entry list.
858     *
859     * @return The count of occurrences of the type in the entry list. 0 if entries is
860     * {@literal null}
861     */
862    private static int getEntryCountByType(ArrayList<ValuesDelta> entries, String typeColumn,
863            int type) {
864        int count = 0;
865        if (entries != null) {
866            for (ValuesDelta entry : entries) {
867                Integer typeInteger = entry.getAsInteger(typeColumn);
868                if (typeInteger != null && typeInteger == type) {
869                    count++;
870                }
871            }
872        }
873        return count;
874    }
875
876    /**
877     * Attempt to parse legacy {@link Insert#IM_PROTOCOL} values, replacing them
878     * with updated values.
879     */
880    @SuppressWarnings("deprecation")
881    private static void fixupLegacyImType(Bundle bundle) {
882        final String encodedString = bundle.getString(Insert.IM_PROTOCOL);
883        if (encodedString == null) return;
884
885        try {
886            final Object protocol = android.provider.Contacts.ContactMethods
887                    .decodeImProtocol(encodedString);
888            if (protocol instanceof Integer) {
889                bundle.putInt(Insert.IM_PROTOCOL, (Integer)protocol);
890            } else {
891                bundle.putString(Insert.IM_PROTOCOL, (String)protocol);
892            }
893        } catch (IllegalArgumentException e) {
894            // Ignore exception when legacy parser fails
895        }
896    }
897
898    /**
899     * Parse a specific entry from the given {@link Bundle} and insert into the
900     * given {@link RawContactDelta}. Silently skips the insert when missing value
901     * or no valid {@link EditType} found.
902     *
903     * @param typeExtra {@link Bundle} key that holds the incoming
904     *            {@link EditType#rawValue} value.
905     * @param valueExtra {@link Bundle} key that holds the incoming value.
906     * @param valueColumn Column to write value into {@link ValuesDelta}.
907     */
908    public static ValuesDelta parseExtras(RawContactDelta state, DataKind kind, Bundle extras,
909            String typeExtra, String valueExtra, String valueColumn) {
910        final CharSequence value = extras.getCharSequence(valueExtra);
911
912        // Bail early if account type doesn't handle this MIME type
913        if (kind == null) return null;
914
915        // Bail when can't insert type, or value missing
916        final boolean canInsert = RawContactModifier.canInsert(state, kind);
917        final boolean validValue = (value != null && TextUtils.isGraphic(value));
918        if (!validValue || !canInsert) return null;
919
920        // Find exact type when requested, otherwise best available type
921        final boolean hasType = extras.containsKey(typeExtra);
922        final int typeValue = extras.getInt(typeExtra, hasType ? BaseTypes.TYPE_CUSTOM
923                : Integer.MIN_VALUE);
924        final EditType editType = RawContactModifier.getBestValidType(state, kind, true, typeValue);
925
926        // Create data row and fill with value
927        final ValuesDelta child = RawContactModifier.insertChild(state, kind, editType);
928        child.put(valueColumn, value.toString());
929
930        if (editType != null && editType.customColumn != null) {
931            // Write down label when custom type picked
932            final String customType = extras.getString(typeExtra);
933            child.put(editType.customColumn, customType);
934        }
935
936        return child;
937    }
938
939    /**
940     * Generic mime types with type support (e.g. TYPE_HOME).
941     * Here, "type support" means if the data kind has CommonColumns#TYPE or not. Data kinds which
942     * have their own migrate methods aren't listed here.
943     */
944    private static final Set<String> sGenericMimeTypesWithTypeSupport = new HashSet<String>(
945            Arrays.asList(Phone.CONTENT_ITEM_TYPE,
946                    Email.CONTENT_ITEM_TYPE,
947                    Im.CONTENT_ITEM_TYPE,
948                    Nickname.CONTENT_ITEM_TYPE,
949                    Website.CONTENT_ITEM_TYPE,
950                    Relation.CONTENT_ITEM_TYPE,
951                    SipAddress.CONTENT_ITEM_TYPE));
952    private static final Set<String> sGenericMimeTypesWithoutTypeSupport = new HashSet<String>(
953            Arrays.asList(Organization.CONTENT_ITEM_TYPE,
954                    Note.CONTENT_ITEM_TYPE,
955                    Photo.CONTENT_ITEM_TYPE,
956                    GroupMembership.CONTENT_ITEM_TYPE));
957    // CommonColumns.TYPE cannot be accessed as it is protected interface, so use
958    // Phone.TYPE instead.
959    private static final String COLUMN_FOR_TYPE  = Phone.TYPE;
960    private static final String COLUMN_FOR_LABEL  = Phone.LABEL;
961    private static final int TYPE_CUSTOM = Phone.TYPE_CUSTOM;
962
963    /**
964     * Migrates old RawContactDelta to newly created one with a new restriction supplied from
965     * newAccountType.
966     *
967     * This is only for account switch during account creation (which must be insert operation).
968     */
969    public static void migrateStateForNewContact(Context context,
970            RawContactDelta oldState, RawContactDelta newState,
971            AccountType oldAccountType, AccountType newAccountType) {
972        if (newAccountType == oldAccountType) {
973            // Just copying all data in oldState isn't enough, but we can still rely on a lot of
974            // shortcuts.
975            for (DataKind kind : newAccountType.getSortedDataKinds()) {
976                final String mimeType = kind.mimeType;
977                // The fields with short/long form capability must be treated properly.
978                if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
979                    migrateStructuredName(context, oldState, newState, kind);
980                } else {
981                    List<ValuesDelta> entryList = oldState.getMimeEntries(mimeType);
982                    if (entryList != null && !entryList.isEmpty()) {
983                        for (ValuesDelta entry : entryList) {
984                            ContentValues values = entry.getAfter();
985                            if (values != null) {
986                                newState.addEntry(ValuesDelta.fromAfter(values));
987                            }
988                        }
989                    }
990                }
991            }
992        } else {
993            // Migrate data supported by the new account type.
994            // All the other data inside oldState are silently dropped.
995            for (DataKind kind : newAccountType.getSortedDataKinds()) {
996                if (!kind.editable) continue;
997                final String mimeType = kind.mimeType;
998                if (DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME.equals(mimeType)
999                        || DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME.equals(mimeType)) {
1000                    // Ignore pseudo data.
1001                    continue;
1002                } else if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
1003                    migrateStructuredName(context, oldState, newState, kind);
1004                } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType)) {
1005                    migratePostal(oldState, newState, kind);
1006                } else if (Event.CONTENT_ITEM_TYPE.equals(mimeType)) {
1007                    migrateEvent(oldState, newState, kind, null /* default Year */);
1008                } else if (sGenericMimeTypesWithoutTypeSupport.contains(mimeType)) {
1009                    migrateGenericWithoutTypeColumn(oldState, newState, kind);
1010                } else if (sGenericMimeTypesWithTypeSupport.contains(mimeType)) {
1011                    migrateGenericWithTypeColumn(oldState, newState, kind);
1012                } else {
1013                    throw new IllegalStateException("Unexpected editable mime-type: " + mimeType);
1014                }
1015            }
1016        }
1017    }
1018
1019    /**
1020     * Checks {@link DataKind#isList} and {@link DataKind#typeOverallMax}, and restricts
1021     * the number of entries (ValuesDelta) inside newState.
1022     */
1023    private static ArrayList<ValuesDelta> ensureEntryMaxSize(RawContactDelta newState,
1024            DataKind kind, ArrayList<ValuesDelta> mimeEntries) {
1025        if (mimeEntries == null) {
1026            return null;
1027        }
1028
1029        final int typeOverallMax = kind.typeOverallMax;
1030        if (typeOverallMax >= 0 && (mimeEntries.size() > typeOverallMax)) {
1031            ArrayList<ValuesDelta> newMimeEntries = new ArrayList<ValuesDelta>(typeOverallMax);
1032            for (int i = 0; i < typeOverallMax; i++) {
1033                newMimeEntries.add(mimeEntries.get(i));
1034            }
1035            mimeEntries = newMimeEntries;
1036        }
1037        return mimeEntries;
1038    }
1039
1040    /** @hide Public only for testing. */
1041    public static void migrateStructuredName(
1042            Context context, RawContactDelta oldState, RawContactDelta newState,
1043            DataKind newDataKind) {
1044        final ContentValues values =
1045                oldState.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE).getAfter();
1046        if (values == null) {
1047            return;
1048        }
1049
1050        boolean supportDisplayName = false;
1051        boolean supportPhoneticFullName = false;
1052        boolean supportPhoneticFamilyName = false;
1053        boolean supportPhoneticMiddleName = false;
1054        boolean supportPhoneticGivenName = false;
1055        for (EditField editField : newDataKind.fieldList) {
1056            if (StructuredName.DISPLAY_NAME.equals(editField.column)) {
1057                supportDisplayName = true;
1058            }
1059            if (DataKind.PSEUDO_COLUMN_PHONETIC_NAME.equals(editField.column)) {
1060                supportPhoneticFullName = true;
1061            }
1062            if (StructuredName.PHONETIC_FAMILY_NAME.equals(editField.column)) {
1063                supportPhoneticFamilyName = true;
1064            }
1065            if (StructuredName.PHONETIC_MIDDLE_NAME.equals(editField.column)) {
1066                supportPhoneticMiddleName = true;
1067            }
1068            if (StructuredName.PHONETIC_GIVEN_NAME.equals(editField.column)) {
1069                supportPhoneticGivenName = true;
1070            }
1071        }
1072
1073        // DISPLAY_NAME <-> PREFIX, GIVEN_NAME, MIDDLE_NAME, FAMILY_NAME, SUFFIX
1074        final String displayName = values.getAsString(StructuredName.DISPLAY_NAME);
1075        if (!TextUtils.isEmpty(displayName)) {
1076            if (!supportDisplayName) {
1077                // Old data has a display name, while the new account doesn't allow it.
1078                NameConverter.displayNameToStructuredName(context, displayName, values);
1079
1080                // We don't want to migrate unseen data which may confuse users after the creation.
1081                values.remove(StructuredName.DISPLAY_NAME);
1082            }
1083        } else {
1084            if (supportDisplayName) {
1085                // Old data does not have display name, while the new account requires it.
1086                values.put(StructuredName.DISPLAY_NAME,
1087                        NameConverter.structuredNameToDisplayName(context, values));
1088                for (String field : NameConverter.STRUCTURED_NAME_FIELDS) {
1089                    values.remove(field);
1090                }
1091            }
1092        }
1093
1094        // Phonetic (full) name <-> PHONETIC_FAMILY_NAME, PHONETIC_MIDDLE_NAME, PHONETIC_GIVEN_NAME
1095        final String phoneticFullName = values.getAsString(DataKind.PSEUDO_COLUMN_PHONETIC_NAME);
1096        if (!TextUtils.isEmpty(phoneticFullName)) {
1097            if (!supportPhoneticFullName) {
1098                // Old data has a phonetic (full) name, while the new account doesn't allow it.
1099                final StructuredNameDataItem tmpItem =
1100                        NameConverter.parsePhoneticName(phoneticFullName, null);
1101                values.remove(DataKind.PSEUDO_COLUMN_PHONETIC_NAME);
1102                if (supportPhoneticFamilyName) {
1103                    values.put(StructuredName.PHONETIC_FAMILY_NAME,
1104                            tmpItem.getPhoneticFamilyName());
1105                } else {
1106                    values.remove(StructuredName.PHONETIC_FAMILY_NAME);
1107                }
1108                if (supportPhoneticMiddleName) {
1109                    values.put(StructuredName.PHONETIC_MIDDLE_NAME,
1110                            tmpItem.getPhoneticMiddleName());
1111                } else {
1112                    values.remove(StructuredName.PHONETIC_MIDDLE_NAME);
1113                }
1114                if (supportPhoneticGivenName) {
1115                    values.put(StructuredName.PHONETIC_GIVEN_NAME,
1116                            tmpItem.getPhoneticGivenName());
1117                } else {
1118                    values.remove(StructuredName.PHONETIC_GIVEN_NAME);
1119                }
1120            }
1121        } else {
1122            if (supportPhoneticFullName) {
1123                // Old data does not have a phonetic (full) name, while the new account requires it.
1124                values.put(DataKind.PSEUDO_COLUMN_PHONETIC_NAME,
1125                        NameConverter.buildPhoneticName(
1126                                values.getAsString(StructuredName.PHONETIC_FAMILY_NAME),
1127                                values.getAsString(StructuredName.PHONETIC_MIDDLE_NAME),
1128                                values.getAsString(StructuredName.PHONETIC_GIVEN_NAME)));
1129            }
1130            if (!supportPhoneticFamilyName) {
1131                values.remove(StructuredName.PHONETIC_FAMILY_NAME);
1132            }
1133            if (!supportPhoneticMiddleName) {
1134                values.remove(StructuredName.PHONETIC_MIDDLE_NAME);
1135            }
1136            if (!supportPhoneticGivenName) {
1137                values.remove(StructuredName.PHONETIC_GIVEN_NAME);
1138            }
1139        }
1140
1141        newState.addEntry(ValuesDelta.fromAfter(values));
1142    }
1143
1144    /** @hide Public only for testing. */
1145    public static void migratePostal(RawContactDelta oldState, RawContactDelta newState,
1146            DataKind newDataKind) {
1147        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1148                oldState.getMimeEntries(StructuredPostal.CONTENT_ITEM_TYPE));
1149        if (mimeEntries == null || mimeEntries.isEmpty()) {
1150            return;
1151        }
1152
1153        boolean supportFormattedAddress = false;
1154        boolean supportStreet = false;
1155        final String firstColumn = newDataKind.fieldList.get(0).column;
1156        for (EditField editField : newDataKind.fieldList) {
1157            if (StructuredPostal.FORMATTED_ADDRESS.equals(editField.column)) {
1158                supportFormattedAddress = true;
1159            }
1160            if (StructuredPostal.STREET.equals(editField.column)) {
1161                supportStreet = true;
1162            }
1163        }
1164
1165        final Set<Integer> supportedTypes = new HashSet<Integer>();
1166        if (newDataKind.typeList != null && !newDataKind.typeList.isEmpty()) {
1167            for (EditType editType : newDataKind.typeList) {
1168                supportedTypes.add(editType.rawValue);
1169            }
1170        }
1171
1172        for (ValuesDelta entry : mimeEntries) {
1173            final ContentValues values = entry.getAfter();
1174            if (values == null) {
1175                continue;
1176            }
1177            final Integer oldType = values.getAsInteger(StructuredPostal.TYPE);
1178            if (!supportedTypes.contains(oldType)) {
1179                int defaultType;
1180                if (newDataKind.defaultValues != null) {
1181                    defaultType = newDataKind.defaultValues.getAsInteger(StructuredPostal.TYPE);
1182                } else {
1183                    defaultType = newDataKind.typeList.get(0).rawValue;
1184                }
1185                values.put(StructuredPostal.TYPE, defaultType);
1186                if (oldType != null && oldType == StructuredPostal.TYPE_CUSTOM) {
1187                    values.remove(StructuredPostal.LABEL);
1188                }
1189            }
1190
1191            final String formattedAddress = values.getAsString(StructuredPostal.FORMATTED_ADDRESS);
1192            if (!TextUtils.isEmpty(formattedAddress)) {
1193                if (!supportFormattedAddress) {
1194                    // Old data has a formatted address, while the new account doesn't allow it.
1195                    values.remove(StructuredPostal.FORMATTED_ADDRESS);
1196
1197                    // Unlike StructuredName we don't have logic to split it, so first
1198                    // try to use street field and. If the new account doesn't have one,
1199                    // then select first one anyway.
1200                    if (supportStreet) {
1201                        values.put(StructuredPostal.STREET, formattedAddress);
1202                    } else {
1203                        values.put(firstColumn, formattedAddress);
1204                    }
1205                }
1206            } else {
1207                if (supportFormattedAddress) {
1208                    // Old data does not have formatted address, while the new account requires it.
1209                    // Unlike StructuredName we don't have logic to join multiple address values.
1210                    // Use poor join heuristics for now.
1211                    String[] structuredData;
1212                    final boolean useJapaneseOrder =
1213                            Locale.JAPANESE.getLanguage().equals(Locale.getDefault().getLanguage());
1214                    if (useJapaneseOrder) {
1215                        structuredData = new String[] {
1216                                values.getAsString(StructuredPostal.COUNTRY),
1217                                values.getAsString(StructuredPostal.POSTCODE),
1218                                values.getAsString(StructuredPostal.REGION),
1219                                values.getAsString(StructuredPostal.CITY),
1220                                values.getAsString(StructuredPostal.NEIGHBORHOOD),
1221                                values.getAsString(StructuredPostal.STREET),
1222                                values.getAsString(StructuredPostal.POBOX) };
1223                    } else {
1224                        structuredData = new String[] {
1225                                values.getAsString(StructuredPostal.POBOX),
1226                                values.getAsString(StructuredPostal.STREET),
1227                                values.getAsString(StructuredPostal.NEIGHBORHOOD),
1228                                values.getAsString(StructuredPostal.CITY),
1229                                values.getAsString(StructuredPostal.REGION),
1230                                values.getAsString(StructuredPostal.POSTCODE),
1231                                values.getAsString(StructuredPostal.COUNTRY) };
1232                    }
1233                    final StringBuilder builder = new StringBuilder();
1234                    for (String elem : structuredData) {
1235                        if (!TextUtils.isEmpty(elem)) {
1236                            builder.append(elem + "\n");
1237                        }
1238                    }
1239                    values.put(StructuredPostal.FORMATTED_ADDRESS, builder.toString());
1240
1241                    values.remove(StructuredPostal.POBOX);
1242                    values.remove(StructuredPostal.STREET);
1243                    values.remove(StructuredPostal.NEIGHBORHOOD);
1244                    values.remove(StructuredPostal.CITY);
1245                    values.remove(StructuredPostal.REGION);
1246                    values.remove(StructuredPostal.POSTCODE);
1247                    values.remove(StructuredPostal.COUNTRY);
1248                }
1249            }
1250
1251            newState.addEntry(ValuesDelta.fromAfter(values));
1252        }
1253    }
1254
1255    /** @hide Public only for testing. */
1256    public static void migrateEvent(RawContactDelta oldState, RawContactDelta newState,
1257            DataKind newDataKind, Integer defaultYear) {
1258        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1259                oldState.getMimeEntries(Event.CONTENT_ITEM_TYPE));
1260        if (mimeEntries == null || mimeEntries.isEmpty()) {
1261            return;
1262        }
1263
1264        final SparseArray<EventEditType> allowedTypes = new SparseArray<EventEditType>();
1265        for (EditType editType : newDataKind.typeList) {
1266            allowedTypes.put(editType.rawValue, (EventEditType) editType);
1267        }
1268        for (ValuesDelta entry : mimeEntries) {
1269            final ContentValues values = entry.getAfter();
1270            if (values == null) {
1271                continue;
1272            }
1273            final String dateString = values.getAsString(Event.START_DATE);
1274            final Integer type = values.getAsInteger(Event.TYPE);
1275            if (type != null && (allowedTypes.indexOfKey(type) >= 0)
1276                    && !TextUtils.isEmpty(dateString)) {
1277                EventEditType suitableType = allowedTypes.get(type);
1278
1279                final ParsePosition position = new ParsePosition(0);
1280                boolean yearOptional = false;
1281                Date date = CommonDateUtils.DATE_AND_TIME_FORMAT.parse(dateString, position);
1282                if (date == null) {
1283                    yearOptional = true;
1284                    date = CommonDateUtils.NO_YEAR_DATE_FORMAT.parse(dateString, position);
1285                }
1286                if (date != null) {
1287                    if (yearOptional && !suitableType.isYearOptional()) {
1288                        // The new EditType doesn't allow optional year. Supply default.
1289                        final Calendar calendar = Calendar.getInstance(DateUtils.UTC_TIMEZONE,
1290                                Locale.US);
1291                        if (defaultYear == null) {
1292                            defaultYear = calendar.get(Calendar.YEAR);
1293                        }
1294                        calendar.setTime(date);
1295                        final int month = calendar.get(Calendar.MONTH);
1296                        final int day = calendar.get(Calendar.DAY_OF_MONTH);
1297                        // Exchange requires 8:00 for birthdays
1298                        calendar.set(defaultYear, month, day,
1299                                CommonDateUtils.DEFAULT_HOUR, 0, 0);
1300                        values.put(Event.START_DATE,
1301                                CommonDateUtils.FULL_DATE_FORMAT.format(calendar.getTime()));
1302                    }
1303                }
1304                newState.addEntry(ValuesDelta.fromAfter(values));
1305            } else {
1306                // Just drop it.
1307            }
1308        }
1309    }
1310
1311    /** @hide Public only for testing. */
1312    public static void migrateGenericWithoutTypeColumn(
1313            RawContactDelta oldState, RawContactDelta newState, DataKind newDataKind) {
1314        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1315                oldState.getMimeEntries(newDataKind.mimeType));
1316        if (mimeEntries == null || mimeEntries.isEmpty()) {
1317            return;
1318        }
1319
1320        for (ValuesDelta entry : mimeEntries) {
1321            ContentValues values = entry.getAfter();
1322            if (values != null) {
1323                newState.addEntry(ValuesDelta.fromAfter(values));
1324            }
1325        }
1326    }
1327
1328    /** @hide Public only for testing. */
1329    public static void migrateGenericWithTypeColumn(
1330            RawContactDelta oldState, RawContactDelta newState, DataKind newDataKind) {
1331        final ArrayList<ValuesDelta> mimeEntries = oldState.getMimeEntries(newDataKind.mimeType);
1332        if (mimeEntries == null || mimeEntries.isEmpty()) {
1333            return;
1334        }
1335
1336        // Note that type specified with the old account may be invalid with the new account, while
1337        // we want to preserve its data as much as possible. e.g. if a user typed a phone number
1338        // with a type which is valid with an old account but not with a new account, the user
1339        // probably wants to have the number with default type, rather than seeing complete data
1340        // loss.
1341        //
1342        // Specifically, this method works as follows:
1343        // 1. detect defaultType
1344        // 2. prepare constants & variables for iteration
1345        // 3. iterate over mimeEntries:
1346        // 3.1 stop iteration if total number of mimeEntries reached typeOverallMax specified in
1347        //     DataKind
1348        // 3.2 replace unallowed types with defaultType
1349        // 3.3 check if the number of entries is below specificMax specified in AccountType
1350
1351        // Here, defaultType can be supplied in two ways
1352        // - via kind.defaultValues
1353        // - via kind.typeList.get(0).rawValue
1354        Integer defaultType = null;
1355        if (newDataKind.defaultValues != null) {
1356            defaultType = newDataKind.defaultValues.getAsInteger(COLUMN_FOR_TYPE);
1357        }
1358        final Set<Integer> allowedTypes = new HashSet<Integer>();
1359        // key: type, value: the number of entries allowed for the type (specificMax)
1360        final SparseIntArray typeSpecificMaxMap = new SparseIntArray();
1361        if (defaultType != null) {
1362            allowedTypes.add(defaultType);
1363            typeSpecificMaxMap.put(defaultType, -1);
1364        }
1365        // Note: typeList may be used in different purposes when defaultValues are specified.
1366        // Especially in IM, typeList contains available protocols (e.g. PROTOCOL_GOOGLE_TALK)
1367        // instead of "types" which we want to treate here (e.g. TYPE_HOME). So we don't add
1368        // anything other than defaultType into allowedTypes and typeSpecificMapMax.
1369        if (!Im.CONTENT_ITEM_TYPE.equals(newDataKind.mimeType) &&
1370                newDataKind.typeList != null && !newDataKind.typeList.isEmpty()) {
1371            for (EditType editType : newDataKind.typeList) {
1372                allowedTypes.add(editType.rawValue);
1373                typeSpecificMaxMap.put(editType.rawValue, editType.specificMax);
1374            }
1375            if (defaultType == null) {
1376                defaultType = newDataKind.typeList.get(0).rawValue;
1377            }
1378        }
1379
1380        if (defaultType == null) {
1381            Log.w(TAG, "Default type isn't available for mimetype " + newDataKind.mimeType);
1382        }
1383
1384        final int typeOverallMax = newDataKind.typeOverallMax;
1385
1386        // key: type, value: the number of current entries.
1387        final SparseIntArray currentEntryCount = new SparseIntArray();
1388        int totalCount = 0;
1389
1390        for (ValuesDelta entry : mimeEntries) {
1391            if (typeOverallMax != -1 && totalCount >= typeOverallMax) {
1392                break;
1393            }
1394
1395            final ContentValues values = entry.getAfter();
1396            if (values == null) {
1397                continue;
1398            }
1399
1400            final Integer oldType = entry.getAsInteger(COLUMN_FOR_TYPE);
1401            final Integer typeForNewAccount;
1402            if (!allowedTypes.contains(oldType)) {
1403                // The new account doesn't support the type.
1404                if (defaultType != null) {
1405                    typeForNewAccount = defaultType.intValue();
1406                    values.put(COLUMN_FOR_TYPE, defaultType.intValue());
1407                    if (oldType != null && oldType == TYPE_CUSTOM) {
1408                        values.remove(COLUMN_FOR_LABEL);
1409                    }
1410                } else {
1411                    typeForNewAccount = null;
1412                    values.remove(COLUMN_FOR_TYPE);
1413                }
1414            } else {
1415                typeForNewAccount = oldType;
1416            }
1417            if (typeForNewAccount != null) {
1418                final int specificMax = typeSpecificMaxMap.get(typeForNewAccount, 0);
1419                if (specificMax >= 0) {
1420                    final int currentCount = currentEntryCount.get(typeForNewAccount, 0);
1421                    if (currentCount >= specificMax) {
1422                        continue;
1423                    }
1424                    currentEntryCount.put(typeForNewAccount, currentCount + 1);
1425                }
1426            }
1427            newState.addEntry(ValuesDelta.fromAfter(values));
1428            totalCount++;
1429        }
1430    }
1431}
1432