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.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        // First try finding a valid primary
351        EditType bestType = getBestValidType(state, kind, false, Integer.MIN_VALUE);
352        if (bestType == null) {
353            // No valid primary found, so expand search to secondary
354            bestType = getBestValidType(state, kind, true, Integer.MIN_VALUE);
355        }
356        return insertChild(state, kind, bestType);
357    }
358
359    /**
360     * Insert a new child of kind {@link DataKind} into the given
361     * {@link RawContactDelta}, marked with the given {@link EditType}.
362     */
363    public static ValuesDelta insertChild(RawContactDelta state, DataKind kind, EditType type) {
364        // Bail early if invalid kind
365        if (kind == null) return null;
366        final ContentValues after = new ContentValues();
367
368        // Our parent CONTACT_ID is provided later
369        after.put(Data.MIMETYPE, kind.mimeType);
370
371        // Fill-in with any requested default values
372        if (kind.defaultValues != null) {
373            after.putAll(kind.defaultValues);
374        }
375
376        if (kind.typeColumn != null && type != null) {
377            // Set type, if provided
378            after.put(kind.typeColumn, type.rawValue);
379        }
380
381        final ValuesDelta child = ValuesDelta.fromAfter(after);
382        state.addEntry(child);
383        return child;
384    }
385
386    /**
387     * Processing to trim any empty {@link ValuesDelta} and {@link RawContactDelta}
388     * from the given {@link RawContactDeltaList}, assuming the given {@link AccountTypeManager}
389     * dictates the structure for various fields. This method ignores rows not
390     * described by the {@link AccountType}.
391     */
392    public static void trimEmpty(RawContactDeltaList set, AccountTypeManager accountTypes) {
393        for (RawContactDelta state : set) {
394            ValuesDelta values = state.getValues();
395            final String accountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
396            final String dataSet = values.getAsString(RawContacts.DATA_SET);
397            final AccountType type = accountTypes.getAccountType(accountType, dataSet);
398            trimEmpty(state, type);
399        }
400    }
401
402    public static boolean hasChanges(RawContactDeltaList set, AccountTypeManager accountTypes) {
403        if (set.isMarkedForSplitting() || set.isMarkedForJoining()) {
404            return true;
405        }
406
407        for (RawContactDelta state : set) {
408            ValuesDelta values = state.getValues();
409            final String accountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
410            final String dataSet = values.getAsString(RawContacts.DATA_SET);
411            final AccountType type = accountTypes.getAccountType(accountType, dataSet);
412            if (hasChanges(state, type)) {
413                return true;
414            }
415        }
416        return false;
417    }
418
419    /**
420     * Processing to trim any empty {@link ValuesDelta} rows from the given
421     * {@link RawContactDelta}, assuming the given {@link AccountType} dictates
422     * the structure for various fields. This method ignores rows not described
423     * by the {@link AccountType}.
424     */
425    public static void trimEmpty(RawContactDelta state, AccountType accountType) {
426        boolean hasValues = false;
427
428        // Walk through entries for each well-known kind
429        for (DataKind kind : accountType.getSortedDataKinds()) {
430            final String mimeType = kind.mimeType;
431            final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
432            if (entries == null) continue;
433
434            for (ValuesDelta entry : entries) {
435                // Skip any values that haven't been touched
436                final boolean touched = entry.isInsert() || entry.isUpdate();
437                if (!touched) {
438                    hasValues = true;
439                    continue;
440                }
441
442                // Test and remove this row if empty and it isn't a photo from google
443                final boolean isGoogleAccount = TextUtils.equals(GoogleAccountType.ACCOUNT_TYPE,
444                        state.getValues().getAsString(RawContacts.ACCOUNT_TYPE));
445                final boolean isPhoto = TextUtils.equals(Photo.CONTENT_ITEM_TYPE, kind.mimeType);
446                final boolean isGooglePhoto = isPhoto && isGoogleAccount;
447
448                if (RawContactModifier.isEmpty(entry, kind) && !isGooglePhoto) {
449                    if (DEBUG) {
450                        Log.v(TAG, "Trimming: " + entry.toString());
451                    }
452                    entry.markDeleted();
453                } else if (!entry.isFromTemplate()) {
454                    hasValues = true;
455                }
456            }
457        }
458        if (!hasValues) {
459            // Trim overall entity if no children exist
460            state.markDeleted();
461        }
462    }
463
464    private static boolean hasChanges(RawContactDelta state, AccountType accountType) {
465        for (DataKind kind : accountType.getSortedDataKinds()) {
466            final String mimeType = kind.mimeType;
467            final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
468            if (entries == null) continue;
469
470            for (ValuesDelta entry : entries) {
471                // An empty Insert must be ignored, because it won't save anything (an example
472                // is an empty name that stays empty)
473                final boolean isRealInsert = entry.isInsert() && !isEmpty(entry, kind);
474                if (isRealInsert || entry.isUpdate() || entry.isDelete()) {
475                    return true;
476                }
477            }
478        }
479        return false;
480    }
481
482    /**
483     * Test if the given {@link ValuesDelta} would be considered "empty" in
484     * terms of {@link DataKind#fieldList}.
485     */
486    public static boolean isEmpty(ValuesDelta values, DataKind kind) {
487        if (Photo.CONTENT_ITEM_TYPE.equals(kind.mimeType)) {
488            return values.isInsert() && values.getAsByteArray(Photo.PHOTO) == null;
489        }
490
491        // No defined fields mean this row is always empty
492        if (kind.fieldList == null) return true;
493
494        for (EditField field : kind.fieldList) {
495            // If any field has values, we're not empty
496            final String value = values.getAsString(field.column);
497            if (ContactsUtils.isGraphic(value)) {
498                return false;
499            }
500        }
501
502        return true;
503    }
504
505    /**
506     * Compares corresponding fields in values1 and values2. Only the fields
507     * declared by the DataKind are taken into consideration.
508     */
509    protected static boolean areEqual(ValuesDelta values1, ContentValues values2, DataKind kind) {
510        if (kind.fieldList == null) return false;
511
512        for (EditField field : kind.fieldList) {
513            final String value1 = values1.getAsString(field.column);
514            final String value2 = values2.getAsString(field.column);
515            if (!TextUtils.equals(value1, value2)) {
516                return false;
517            }
518        }
519
520        return true;
521    }
522
523    /**
524     * Parse the given {@link Bundle} into the given {@link RawContactDelta} state,
525     * assuming the extras defined through {@link Intents}.
526     */
527    public static void parseExtras(Context context, AccountType accountType, RawContactDelta state,
528            Bundle extras) {
529        if (extras == null || extras.size() == 0) {
530            // Bail early if no useful data
531            return;
532        }
533
534        parseStructuredNameExtra(context, accountType, state, extras);
535        parseStructuredPostalExtra(accountType, state, extras);
536
537        {
538            // Phone
539            final DataKind kind = accountType.getKindForMimetype(Phone.CONTENT_ITEM_TYPE);
540            parseExtras(state, kind, extras, Insert.PHONE_TYPE, Insert.PHONE, Phone.NUMBER);
541            parseExtras(state, kind, extras, Insert.SECONDARY_PHONE_TYPE, Insert.SECONDARY_PHONE,
542                    Phone.NUMBER);
543            parseExtras(state, kind, extras, Insert.TERTIARY_PHONE_TYPE, Insert.TERTIARY_PHONE,
544                    Phone.NUMBER);
545        }
546
547        {
548            // Email
549            final DataKind kind = accountType.getKindForMimetype(Email.CONTENT_ITEM_TYPE);
550            parseExtras(state, kind, extras, Insert.EMAIL_TYPE, Insert.EMAIL, Email.DATA);
551            parseExtras(state, kind, extras, Insert.SECONDARY_EMAIL_TYPE, Insert.SECONDARY_EMAIL,
552                    Email.DATA);
553            parseExtras(state, kind, extras, Insert.TERTIARY_EMAIL_TYPE, Insert.TERTIARY_EMAIL,
554                    Email.DATA);
555        }
556
557        {
558            // Im
559            final DataKind kind = accountType.getKindForMimetype(Im.CONTENT_ITEM_TYPE);
560            fixupLegacyImType(extras);
561            parseExtras(state, kind, extras, Insert.IM_PROTOCOL, Insert.IM_HANDLE, Im.DATA);
562        }
563
564        // Organization
565        final boolean hasOrg = extras.containsKey(Insert.COMPANY)
566                || extras.containsKey(Insert.JOB_TITLE);
567        final DataKind kindOrg = accountType.getKindForMimetype(Organization.CONTENT_ITEM_TYPE);
568        if (hasOrg && RawContactModifier.canInsert(state, kindOrg)) {
569            final ValuesDelta child = RawContactModifier.insertChild(state, kindOrg);
570
571            final String company = extras.getString(Insert.COMPANY);
572            if (ContactsUtils.isGraphic(company)) {
573                child.put(Organization.COMPANY, company);
574            }
575
576            final String title = extras.getString(Insert.JOB_TITLE);
577            if (ContactsUtils.isGraphic(title)) {
578                child.put(Organization.TITLE, title);
579            }
580        }
581
582        // Notes
583        final boolean hasNotes = extras.containsKey(Insert.NOTES);
584        final DataKind kindNotes = accountType.getKindForMimetype(Note.CONTENT_ITEM_TYPE);
585        if (hasNotes && RawContactModifier.canInsert(state, kindNotes)) {
586            final ValuesDelta child = RawContactModifier.insertChild(state, kindNotes);
587
588            final String notes = extras.getString(Insert.NOTES);
589            if (ContactsUtils.isGraphic(notes)) {
590                child.put(Note.NOTE, notes);
591            }
592        }
593
594        // Arbitrary additional data
595        ArrayList<ContentValues> values = extras.getParcelableArrayList(Insert.DATA);
596        if (values != null) {
597            parseValues(state, accountType, values);
598        }
599    }
600
601    private static void parseStructuredNameExtra(
602            Context context, AccountType accountType, RawContactDelta state, Bundle extras) {
603        // StructuredName
604        RawContactModifier.ensureKindExists(state, accountType, StructuredName.CONTENT_ITEM_TYPE);
605        final ValuesDelta child = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE);
606
607        final String name = extras.getString(Insert.NAME);
608        if (ContactsUtils.isGraphic(name)) {
609            final DataKind kind = accountType.getKindForMimetype(StructuredName.CONTENT_ITEM_TYPE);
610            boolean supportsDisplayName = false;
611            if (kind.fieldList != null) {
612                for (EditField field : kind.fieldList) {
613                    if (StructuredName.DISPLAY_NAME.equals(field.column)) {
614                        supportsDisplayName = true;
615                        break;
616                    }
617                }
618            }
619
620            if (supportsDisplayName) {
621                child.put(StructuredName.DISPLAY_NAME, name);
622            } else {
623                Uri uri = ContactsContract.AUTHORITY_URI.buildUpon()
624                        .appendPath("complete_name")
625                        .appendQueryParameter(StructuredName.DISPLAY_NAME, name)
626                        .build();
627                Cursor cursor = context.getContentResolver().query(uri,
628                        new String[]{
629                                StructuredName.PREFIX,
630                                StructuredName.GIVEN_NAME,
631                                StructuredName.MIDDLE_NAME,
632                                StructuredName.FAMILY_NAME,
633                                StructuredName.SUFFIX,
634                        }, null, null, null);
635
636                try {
637                    if (cursor.moveToFirst()) {
638                        child.put(StructuredName.PREFIX, cursor.getString(0));
639                        child.put(StructuredName.GIVEN_NAME, cursor.getString(1));
640                        child.put(StructuredName.MIDDLE_NAME, cursor.getString(2));
641                        child.put(StructuredName.FAMILY_NAME, cursor.getString(3));
642                        child.put(StructuredName.SUFFIX, cursor.getString(4));
643                    }
644                } finally {
645                    cursor.close();
646                }
647            }
648        }
649
650        final String phoneticName = extras.getString(Insert.PHONETIC_NAME);
651        if (ContactsUtils.isGraphic(phoneticName)) {
652            child.put(StructuredName.PHONETIC_GIVEN_NAME, phoneticName);
653        }
654    }
655
656    private static void parseStructuredPostalExtra(
657            AccountType accountType, RawContactDelta state, Bundle extras) {
658        // StructuredPostal
659        final DataKind kind = accountType.getKindForMimetype(StructuredPostal.CONTENT_ITEM_TYPE);
660        final ValuesDelta child = parseExtras(state, kind, extras, Insert.POSTAL_TYPE,
661                Insert.POSTAL, StructuredPostal.FORMATTED_ADDRESS);
662        String address = child == null ? null
663                : child.getAsString(StructuredPostal.FORMATTED_ADDRESS);
664        if (!TextUtils.isEmpty(address)) {
665            boolean supportsFormatted = false;
666            if (kind.fieldList != null) {
667                for (EditField field : kind.fieldList) {
668                    if (StructuredPostal.FORMATTED_ADDRESS.equals(field.column)) {
669                        supportsFormatted = true;
670                        break;
671                    }
672                }
673            }
674
675            if (!supportsFormatted) {
676                child.put(StructuredPostal.STREET, address);
677                child.putNull(StructuredPostal.FORMATTED_ADDRESS);
678            }
679        }
680    }
681
682    private static void parseValues(
683            RawContactDelta state, AccountType accountType,
684            ArrayList<ContentValues> dataValueList) {
685        for (ContentValues values : dataValueList) {
686            String mimeType = values.getAsString(Data.MIMETYPE);
687            if (TextUtils.isEmpty(mimeType)) {
688                Log.e(TAG, "Mimetype is required. Ignoring: " + values);
689                continue;
690            }
691
692            // Won't override the contact name
693            if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
694                continue;
695            } else if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) {
696                values.remove(PhoneDataItem.KEY_FORMATTED_PHONE_NUMBER);
697                final Integer type = values.getAsInteger(Phone.TYPE);
698                // If the provided phone number provides a custom phone type but not a label,
699                // replace it with mobile (by default) to avoid the "Enter custom label" from
700                // popping up immediately upon entering the ContactEditorFragment
701                if (type != null && type == Phone.TYPE_CUSTOM &&
702                        TextUtils.isEmpty(values.getAsString(Phone.LABEL))) {
703                    values.put(Phone.TYPE, Phone.TYPE_MOBILE);
704                }
705            }
706
707            DataKind kind = accountType.getKindForMimetype(mimeType);
708            if (kind == null) {
709                Log.e(TAG, "Mimetype not supported for account type "
710                        + accountType.getAccountTypeAndDataSet() + ". Ignoring: " + values);
711                continue;
712            }
713
714            ValuesDelta entry = ValuesDelta.fromAfter(values);
715            if (isEmpty(entry, kind)) {
716                continue;
717            }
718
719            ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
720
721            if ((kind.typeOverallMax != 1) || GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
722                // Check for duplicates
723                boolean addEntry = true;
724                int count = 0;
725                if (entries != null && entries.size() > 0) {
726                    for (ValuesDelta delta : entries) {
727                        if (!delta.isDelete()) {
728                            if (areEqual(delta, values, kind)) {
729                                addEntry = false;
730                                break;
731                            }
732                            count++;
733                        }
734                    }
735                }
736
737                if (kind.typeOverallMax != -1 && count >= kind.typeOverallMax) {
738                    Log.e(TAG, "Mimetype allows at most " + kind.typeOverallMax
739                            + " entries. Ignoring: " + values);
740                    addEntry = false;
741                }
742
743                if (addEntry) {
744                    addEntry = adjustType(entry, entries, kind);
745                }
746
747                if (addEntry) {
748                    state.addEntry(entry);
749                }
750            } else {
751                // Non-list entries should not be overridden
752                boolean addEntry = true;
753                if (entries != null && entries.size() > 0) {
754                    for (ValuesDelta delta : entries) {
755                        if (!delta.isDelete() && !isEmpty(delta, kind)) {
756                            addEntry = false;
757                            break;
758                        }
759                    }
760                    if (addEntry) {
761                        for (ValuesDelta delta : entries) {
762                            delta.markDeleted();
763                        }
764                    }
765                }
766
767                if (addEntry) {
768                    addEntry = adjustType(entry, entries, kind);
769                }
770
771                if (addEntry) {
772                    state.addEntry(entry);
773                } else if (Note.CONTENT_ITEM_TYPE.equals(mimeType)){
774                    // Note is most likely to contain large amounts of text
775                    // that we don't want to drop on the ground.
776                    for (ValuesDelta delta : entries) {
777                        if (!isEmpty(delta, kind)) {
778                            delta.put(Note.NOTE, delta.getAsString(Note.NOTE) + "\n"
779                                    + values.getAsString(Note.NOTE));
780                            break;
781                        }
782                    }
783                } else {
784                    Log.e(TAG, "Will not override mimetype " + mimeType + ". Ignoring: "
785                            + values);
786                }
787            }
788        }
789    }
790
791    /**
792     * Checks if the data kind allows addition of another entry (e.g. Exchange only
793     * supports two "work" phone numbers).  If not, tries to switch to one of the
794     * unused types.  If successful, returns true.
795     */
796    private static boolean adjustType(
797            ValuesDelta entry, ArrayList<ValuesDelta> entries, DataKind kind) {
798        if (kind.typeColumn == null || kind.typeList == null || kind.typeList.size() == 0) {
799            return true;
800        }
801
802        Integer typeInteger = entry.getAsInteger(kind.typeColumn);
803        int type = typeInteger != null ? typeInteger : kind.typeList.get(0).rawValue;
804
805        if (isTypeAllowed(type, entries, kind)) {
806            entry.put(kind.typeColumn, type);
807            return true;
808        }
809
810        // Specified type is not allowed - choose the first available type that is allowed
811        int size = kind.typeList.size();
812        for (int i = 0; i < size; i++) {
813            EditType editType = kind.typeList.get(i);
814            if (isTypeAllowed(editType.rawValue, entries, kind)) {
815                entry.put(kind.typeColumn, editType.rawValue);
816                return true;
817            }
818        }
819
820        return false;
821    }
822
823    /**
824     * Checks if a new entry of the specified type can be added to the raw
825     * contact. For example, Exchange only supports two "work" phone numbers, so
826     * addition of a third would not be allowed.
827     */
828    private static boolean isTypeAllowed(int type, ArrayList<ValuesDelta> entries, DataKind kind) {
829        int max = 0;
830        int size = kind.typeList.size();
831        for (int i = 0; i < size; i++) {
832            EditType editType = kind.typeList.get(i);
833            if (editType.rawValue == type) {
834                max = editType.specificMax;
835                break;
836            }
837        }
838
839        if (max == 0) {
840            // This type is not allowed at all
841            return false;
842        }
843
844        if (max == -1) {
845            // Unlimited instances of this type are allowed
846            return true;
847        }
848
849        return getEntryCountByType(entries, kind.typeColumn, type) < max;
850    }
851
852    /**
853     * Counts occurrences of the specified type in the supplied entry list.
854     *
855     * @return The count of occurrences of the type in the entry list. 0 if entries is
856     * {@literal null}
857     */
858    private static int getEntryCountByType(ArrayList<ValuesDelta> entries, String typeColumn,
859            int type) {
860        int count = 0;
861        if (entries != null) {
862            for (ValuesDelta entry : entries) {
863                Integer typeInteger = entry.getAsInteger(typeColumn);
864                if (typeInteger != null && typeInteger == type) {
865                    count++;
866                }
867            }
868        }
869        return count;
870    }
871
872    /**
873     * Attempt to parse legacy {@link Insert#IM_PROTOCOL} values, replacing them
874     * with updated values.
875     */
876    @SuppressWarnings("deprecation")
877    private static void fixupLegacyImType(Bundle bundle) {
878        final String encodedString = bundle.getString(Insert.IM_PROTOCOL);
879        if (encodedString == null) return;
880
881        try {
882            final Object protocol = android.provider.Contacts.ContactMethods
883                    .decodeImProtocol(encodedString);
884            if (protocol instanceof Integer) {
885                bundle.putInt(Insert.IM_PROTOCOL, (Integer)protocol);
886            } else {
887                bundle.putString(Insert.IM_PROTOCOL, (String)protocol);
888            }
889        } catch (IllegalArgumentException e) {
890            // Ignore exception when legacy parser fails
891        }
892    }
893
894    /**
895     * Parse a specific entry from the given {@link Bundle} and insert into the
896     * given {@link RawContactDelta}. Silently skips the insert when missing value
897     * or no valid {@link EditType} found.
898     *
899     * @param typeExtra {@link Bundle} key that holds the incoming
900     *            {@link EditType#rawValue} value.
901     * @param valueExtra {@link Bundle} key that holds the incoming value.
902     * @param valueColumn Column to write value into {@link ValuesDelta}.
903     */
904    public static ValuesDelta parseExtras(RawContactDelta state, DataKind kind, Bundle extras,
905            String typeExtra, String valueExtra, String valueColumn) {
906        final CharSequence value = extras.getCharSequence(valueExtra);
907
908        // Bail early if account type doesn't handle this MIME type
909        if (kind == null) return null;
910
911        // Bail when can't insert type, or value missing
912        final boolean canInsert = RawContactModifier.canInsert(state, kind);
913        final boolean validValue = (value != null && TextUtils.isGraphic(value));
914        if (!validValue || !canInsert) return null;
915
916        // Find exact type when requested, otherwise best available type
917        final boolean hasType = extras.containsKey(typeExtra);
918        final int typeValue = extras.getInt(typeExtra, hasType ? BaseTypes.TYPE_CUSTOM
919                : Integer.MIN_VALUE);
920        final EditType editType = RawContactModifier.getBestValidType(state, kind, true, typeValue);
921
922        // Create data row and fill with value
923        final ValuesDelta child = RawContactModifier.insertChild(state, kind, editType);
924        child.put(valueColumn, value.toString());
925
926        if (editType != null && editType.customColumn != null) {
927            // Write down label when custom type picked
928            final String customType = extras.getString(typeExtra);
929            child.put(editType.customColumn, customType);
930        }
931
932        return child;
933    }
934
935    /**
936     * Generic mime types with type support (e.g. TYPE_HOME).
937     * Here, "type support" means if the data kind has CommonColumns#TYPE or not. Data kinds which
938     * have their own migrate methods aren't listed here.
939     */
940    private static final Set<String> sGenericMimeTypesWithTypeSupport = new HashSet<String>(
941            Arrays.asList(Phone.CONTENT_ITEM_TYPE,
942                    Email.CONTENT_ITEM_TYPE,
943                    Im.CONTENT_ITEM_TYPE,
944                    Nickname.CONTENT_ITEM_TYPE,
945                    Website.CONTENT_ITEM_TYPE,
946                    Relation.CONTENT_ITEM_TYPE,
947                    SipAddress.CONTENT_ITEM_TYPE));
948    private static final Set<String> sGenericMimeTypesWithoutTypeSupport = new HashSet<String>(
949            Arrays.asList(Organization.CONTENT_ITEM_TYPE,
950                    Note.CONTENT_ITEM_TYPE,
951                    Photo.CONTENT_ITEM_TYPE,
952                    GroupMembership.CONTENT_ITEM_TYPE));
953    // CommonColumns.TYPE cannot be accessed as it is protected interface, so use
954    // Phone.TYPE instead.
955    private static final String COLUMN_FOR_TYPE  = Phone.TYPE;
956    private static final String COLUMN_FOR_LABEL  = Phone.LABEL;
957    private static final int TYPE_CUSTOM = Phone.TYPE_CUSTOM;
958
959    /**
960     * Migrates old RawContactDelta to newly created one with a new restriction supplied from
961     * newAccountType.
962     *
963     * This is only for account switch during account creation (which must be insert operation).
964     */
965    public static void migrateStateForNewContact(Context context,
966            RawContactDelta oldState, RawContactDelta newState,
967            AccountType oldAccountType, AccountType newAccountType) {
968        if (newAccountType == oldAccountType) {
969            // Just copying all data in oldState isn't enough, but we can still rely on a lot of
970            // shortcuts.
971            for (DataKind kind : newAccountType.getSortedDataKinds()) {
972                final String mimeType = kind.mimeType;
973                // The fields with short/long form capability must be treated properly.
974                if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
975                    migrateStructuredName(context, oldState, newState, kind);
976                } else {
977                    List<ValuesDelta> entryList = oldState.getMimeEntries(mimeType);
978                    if (entryList != null && !entryList.isEmpty()) {
979                        for (ValuesDelta entry : entryList) {
980                            ContentValues values = entry.getAfter();
981                            if (values != null) {
982                                newState.addEntry(ValuesDelta.fromAfter(values));
983                            }
984                        }
985                    }
986                }
987            }
988        } else {
989            // Migrate data supported by the new account type.
990            // All the other data inside oldState are silently dropped.
991            for (DataKind kind : newAccountType.getSortedDataKinds()) {
992                if (!kind.editable) continue;
993                final String mimeType = kind.mimeType;
994                if (DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME.equals(mimeType)
995                        || DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME.equals(mimeType)) {
996                    // Ignore pseudo data.
997                    continue;
998                } else if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
999                    migrateStructuredName(context, oldState, newState, kind);
1000                } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType)) {
1001                    migratePostal(oldState, newState, kind);
1002                } else if (Event.CONTENT_ITEM_TYPE.equals(mimeType)) {
1003                    migrateEvent(oldState, newState, kind, null /* default Year */);
1004                } else if (sGenericMimeTypesWithoutTypeSupport.contains(mimeType)) {
1005                    migrateGenericWithoutTypeColumn(oldState, newState, kind);
1006                } else if (sGenericMimeTypesWithTypeSupport.contains(mimeType)) {
1007                    migrateGenericWithTypeColumn(oldState, newState, kind);
1008                } else {
1009                    throw new IllegalStateException("Unexpected editable mime-type: " + mimeType);
1010                }
1011            }
1012        }
1013    }
1014
1015    /**
1016     * Checks {@link DataKind#isList} and {@link DataKind#typeOverallMax}, and restricts
1017     * the number of entries (ValuesDelta) inside newState.
1018     */
1019    private static ArrayList<ValuesDelta> ensureEntryMaxSize(RawContactDelta newState,
1020            DataKind kind, ArrayList<ValuesDelta> mimeEntries) {
1021        if (mimeEntries == null) {
1022            return null;
1023        }
1024
1025        final int typeOverallMax = kind.typeOverallMax;
1026        if (typeOverallMax >= 0 && (mimeEntries.size() > typeOverallMax)) {
1027            ArrayList<ValuesDelta> newMimeEntries = new ArrayList<ValuesDelta>(typeOverallMax);
1028            for (int i = 0; i < typeOverallMax; i++) {
1029                newMimeEntries.add(mimeEntries.get(i));
1030            }
1031            mimeEntries = newMimeEntries;
1032        }
1033        return mimeEntries;
1034    }
1035
1036    /** @hide Public only for testing. */
1037    public static void migrateStructuredName(
1038            Context context, RawContactDelta oldState, RawContactDelta newState,
1039            DataKind newDataKind) {
1040        final ContentValues values =
1041                oldState.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE).getAfter();
1042        if (values == null) {
1043            return;
1044        }
1045
1046        boolean supportDisplayName = false;
1047        boolean supportPhoneticFullName = false;
1048        boolean supportPhoneticFamilyName = false;
1049        boolean supportPhoneticMiddleName = false;
1050        boolean supportPhoneticGivenName = false;
1051        for (EditField editField : newDataKind.fieldList) {
1052            if (StructuredName.DISPLAY_NAME.equals(editField.column)) {
1053                supportDisplayName = true;
1054            }
1055            if (DataKind.PSEUDO_COLUMN_PHONETIC_NAME.equals(editField.column)) {
1056                supportPhoneticFullName = true;
1057            }
1058            if (StructuredName.PHONETIC_FAMILY_NAME.equals(editField.column)) {
1059                supportPhoneticFamilyName = true;
1060            }
1061            if (StructuredName.PHONETIC_MIDDLE_NAME.equals(editField.column)) {
1062                supportPhoneticMiddleName = true;
1063            }
1064            if (StructuredName.PHONETIC_GIVEN_NAME.equals(editField.column)) {
1065                supportPhoneticGivenName = true;
1066            }
1067        }
1068
1069        // DISPLAY_NAME <-> PREFIX, GIVEN_NAME, MIDDLE_NAME, FAMILY_NAME, SUFFIX
1070        final String displayName = values.getAsString(StructuredName.DISPLAY_NAME);
1071        if (!TextUtils.isEmpty(displayName)) {
1072            if (!supportDisplayName) {
1073                // Old data has a display name, while the new account doesn't allow it.
1074                NameConverter.displayNameToStructuredName(context, displayName, values);
1075
1076                // We don't want to migrate unseen data which may confuse users after the creation.
1077                values.remove(StructuredName.DISPLAY_NAME);
1078            }
1079        } else {
1080            if (supportDisplayName) {
1081                // Old data does not have display name, while the new account requires it.
1082                values.put(StructuredName.DISPLAY_NAME,
1083                        NameConverter.structuredNameToDisplayName(context, values));
1084                for (String field : NameConverter.STRUCTURED_NAME_FIELDS) {
1085                    values.remove(field);
1086                }
1087            }
1088        }
1089
1090        // Phonetic (full) name <-> PHONETIC_FAMILY_NAME, PHONETIC_MIDDLE_NAME, PHONETIC_GIVEN_NAME
1091        final String phoneticFullName = values.getAsString(DataKind.PSEUDO_COLUMN_PHONETIC_NAME);
1092        if (!TextUtils.isEmpty(phoneticFullName)) {
1093            if (!supportPhoneticFullName) {
1094                // Old data has a phonetic (full) name, while the new account doesn't allow it.
1095                final StructuredNameDataItem tmpItem =
1096                        NameConverter.parsePhoneticName(phoneticFullName, null);
1097                values.remove(DataKind.PSEUDO_COLUMN_PHONETIC_NAME);
1098                if (supportPhoneticFamilyName) {
1099                    values.put(StructuredName.PHONETIC_FAMILY_NAME,
1100                            tmpItem.getPhoneticFamilyName());
1101                } else {
1102                    values.remove(StructuredName.PHONETIC_FAMILY_NAME);
1103                }
1104                if (supportPhoneticMiddleName) {
1105                    values.put(StructuredName.PHONETIC_MIDDLE_NAME,
1106                            tmpItem.getPhoneticMiddleName());
1107                } else {
1108                    values.remove(StructuredName.PHONETIC_MIDDLE_NAME);
1109                }
1110                if (supportPhoneticGivenName) {
1111                    values.put(StructuredName.PHONETIC_GIVEN_NAME,
1112                            tmpItem.getPhoneticGivenName());
1113                } else {
1114                    values.remove(StructuredName.PHONETIC_GIVEN_NAME);
1115                }
1116            }
1117        } else {
1118            if (supportPhoneticFullName) {
1119                // Old data does not have a phonetic (full) name, while the new account requires it.
1120                values.put(DataKind.PSEUDO_COLUMN_PHONETIC_NAME,
1121                        NameConverter.buildPhoneticName(
1122                                values.getAsString(StructuredName.PHONETIC_FAMILY_NAME),
1123                                values.getAsString(StructuredName.PHONETIC_MIDDLE_NAME),
1124                                values.getAsString(StructuredName.PHONETIC_GIVEN_NAME)));
1125            }
1126            if (!supportPhoneticFamilyName) {
1127                values.remove(StructuredName.PHONETIC_FAMILY_NAME);
1128            }
1129            if (!supportPhoneticMiddleName) {
1130                values.remove(StructuredName.PHONETIC_MIDDLE_NAME);
1131            }
1132            if (!supportPhoneticGivenName) {
1133                values.remove(StructuredName.PHONETIC_GIVEN_NAME);
1134            }
1135        }
1136
1137        newState.addEntry(ValuesDelta.fromAfter(values));
1138    }
1139
1140    /** @hide Public only for testing. */
1141    public static void migratePostal(RawContactDelta oldState, RawContactDelta newState,
1142            DataKind newDataKind) {
1143        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1144                oldState.getMimeEntries(StructuredPostal.CONTENT_ITEM_TYPE));
1145        if (mimeEntries == null || mimeEntries.isEmpty()) {
1146            return;
1147        }
1148
1149        boolean supportFormattedAddress = false;
1150        boolean supportStreet = false;
1151        final String firstColumn = newDataKind.fieldList.get(0).column;
1152        for (EditField editField : newDataKind.fieldList) {
1153            if (StructuredPostal.FORMATTED_ADDRESS.equals(editField.column)) {
1154                supportFormattedAddress = true;
1155            }
1156            if (StructuredPostal.STREET.equals(editField.column)) {
1157                supportStreet = true;
1158            }
1159        }
1160
1161        final Set<Integer> supportedTypes = new HashSet<Integer>();
1162        if (newDataKind.typeList != null && !newDataKind.typeList.isEmpty()) {
1163            for (EditType editType : newDataKind.typeList) {
1164                supportedTypes.add(editType.rawValue);
1165            }
1166        }
1167
1168        for (ValuesDelta entry : mimeEntries) {
1169            final ContentValues values = entry.getAfter();
1170            if (values == null) {
1171                continue;
1172            }
1173            final Integer oldType = values.getAsInteger(StructuredPostal.TYPE);
1174            if (!supportedTypes.contains(oldType)) {
1175                int defaultType;
1176                if (newDataKind.defaultValues != null) {
1177                    defaultType = newDataKind.defaultValues.getAsInteger(StructuredPostal.TYPE);
1178                } else {
1179                    defaultType = newDataKind.typeList.get(0).rawValue;
1180                }
1181                values.put(StructuredPostal.TYPE, defaultType);
1182                if (oldType != null && oldType == StructuredPostal.TYPE_CUSTOM) {
1183                    values.remove(StructuredPostal.LABEL);
1184                }
1185            }
1186
1187            final String formattedAddress = values.getAsString(StructuredPostal.FORMATTED_ADDRESS);
1188            if (!TextUtils.isEmpty(formattedAddress)) {
1189                if (!supportFormattedAddress) {
1190                    // Old data has a formatted address, while the new account doesn't allow it.
1191                    values.remove(StructuredPostal.FORMATTED_ADDRESS);
1192
1193                    // Unlike StructuredName we don't have logic to split it, so first
1194                    // try to use street field and. If the new account doesn't have one,
1195                    // then select first one anyway.
1196                    if (supportStreet) {
1197                        values.put(StructuredPostal.STREET, formattedAddress);
1198                    } else {
1199                        values.put(firstColumn, formattedAddress);
1200                    }
1201                }
1202            } else {
1203                if (supportFormattedAddress) {
1204                    // Old data does not have formatted address, while the new account requires it.
1205                    // Unlike StructuredName we don't have logic to join multiple address values.
1206                    // Use poor join heuristics for now.
1207                    String[] structuredData;
1208                    final boolean useJapaneseOrder =
1209                            Locale.JAPANESE.getLanguage().equals(Locale.getDefault().getLanguage());
1210                    if (useJapaneseOrder) {
1211                        structuredData = new String[] {
1212                                values.getAsString(StructuredPostal.COUNTRY),
1213                                values.getAsString(StructuredPostal.POSTCODE),
1214                                values.getAsString(StructuredPostal.REGION),
1215                                values.getAsString(StructuredPostal.CITY),
1216                                values.getAsString(StructuredPostal.NEIGHBORHOOD),
1217                                values.getAsString(StructuredPostal.STREET),
1218                                values.getAsString(StructuredPostal.POBOX) };
1219                    } else {
1220                        structuredData = new String[] {
1221                                values.getAsString(StructuredPostal.POBOX),
1222                                values.getAsString(StructuredPostal.STREET),
1223                                values.getAsString(StructuredPostal.NEIGHBORHOOD),
1224                                values.getAsString(StructuredPostal.CITY),
1225                                values.getAsString(StructuredPostal.REGION),
1226                                values.getAsString(StructuredPostal.POSTCODE),
1227                                values.getAsString(StructuredPostal.COUNTRY) };
1228                    }
1229                    final StringBuilder builder = new StringBuilder();
1230                    for (String elem : structuredData) {
1231                        if (!TextUtils.isEmpty(elem)) {
1232                            builder.append(elem + "\n");
1233                        }
1234                    }
1235                    values.put(StructuredPostal.FORMATTED_ADDRESS, builder.toString());
1236
1237                    values.remove(StructuredPostal.POBOX);
1238                    values.remove(StructuredPostal.STREET);
1239                    values.remove(StructuredPostal.NEIGHBORHOOD);
1240                    values.remove(StructuredPostal.CITY);
1241                    values.remove(StructuredPostal.REGION);
1242                    values.remove(StructuredPostal.POSTCODE);
1243                    values.remove(StructuredPostal.COUNTRY);
1244                }
1245            }
1246
1247            newState.addEntry(ValuesDelta.fromAfter(values));
1248        }
1249    }
1250
1251    /** @hide Public only for testing. */
1252    public static void migrateEvent(RawContactDelta oldState, RawContactDelta newState,
1253            DataKind newDataKind, Integer defaultYear) {
1254        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1255                oldState.getMimeEntries(Event.CONTENT_ITEM_TYPE));
1256        if (mimeEntries == null || mimeEntries.isEmpty()) {
1257            return;
1258        }
1259
1260        final SparseArray<EventEditType> allowedTypes = new SparseArray<EventEditType>();
1261        for (EditType editType : newDataKind.typeList) {
1262            allowedTypes.put(editType.rawValue, (EventEditType) editType);
1263        }
1264        for (ValuesDelta entry : mimeEntries) {
1265            final ContentValues values = entry.getAfter();
1266            if (values == null) {
1267                continue;
1268            }
1269            final String dateString = values.getAsString(Event.START_DATE);
1270            final Integer type = values.getAsInteger(Event.TYPE);
1271            if (type != null && (allowedTypes.indexOfKey(type) >= 0)
1272                    && !TextUtils.isEmpty(dateString)) {
1273                EventEditType suitableType = allowedTypes.get(type);
1274
1275                final ParsePosition position = new ParsePosition(0);
1276                boolean yearOptional = false;
1277                Date date = CommonDateUtils.DATE_AND_TIME_FORMAT.parse(dateString, position);
1278                if (date == null) {
1279                    yearOptional = true;
1280                    date = CommonDateUtils.NO_YEAR_DATE_FORMAT.parse(dateString, position);
1281                }
1282                if (date != null) {
1283                    if (yearOptional && !suitableType.isYearOptional()) {
1284                        // The new EditType doesn't allow optional year. Supply default.
1285                        final Calendar calendar = Calendar.getInstance(DateUtils.UTC_TIMEZONE,
1286                                Locale.US);
1287                        if (defaultYear == null) {
1288                            defaultYear = calendar.get(Calendar.YEAR);
1289                        }
1290                        calendar.setTime(date);
1291                        final int month = calendar.get(Calendar.MONTH);
1292                        final int day = calendar.get(Calendar.DAY_OF_MONTH);
1293                        // Exchange requires 8:00 for birthdays
1294                        calendar.set(defaultYear, month, day,
1295                                CommonDateUtils.DEFAULT_HOUR, 0, 0);
1296                        values.put(Event.START_DATE,
1297                                CommonDateUtils.FULL_DATE_FORMAT.format(calendar.getTime()));
1298                    }
1299                }
1300                newState.addEntry(ValuesDelta.fromAfter(values));
1301            } else {
1302                // Just drop it.
1303            }
1304        }
1305    }
1306
1307    /** @hide Public only for testing. */
1308    public static void migrateGenericWithoutTypeColumn(
1309            RawContactDelta oldState, RawContactDelta newState, DataKind newDataKind) {
1310        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1311                oldState.getMimeEntries(newDataKind.mimeType));
1312        if (mimeEntries == null || mimeEntries.isEmpty()) {
1313            return;
1314        }
1315
1316        for (ValuesDelta entry : mimeEntries) {
1317            ContentValues values = entry.getAfter();
1318            if (values != null) {
1319                newState.addEntry(ValuesDelta.fromAfter(values));
1320            }
1321        }
1322    }
1323
1324    /** @hide Public only for testing. */
1325    public static void migrateGenericWithTypeColumn(
1326            RawContactDelta oldState, RawContactDelta newState, DataKind newDataKind) {
1327        final ArrayList<ValuesDelta> mimeEntries = oldState.getMimeEntries(newDataKind.mimeType);
1328        if (mimeEntries == null || mimeEntries.isEmpty()) {
1329            return;
1330        }
1331
1332        // Note that type specified with the old account may be invalid with the new account, while
1333        // we want to preserve its data as much as possible. e.g. if a user typed a phone number
1334        // with a type which is valid with an old account but not with a new account, the user
1335        // probably wants to have the number with default type, rather than seeing complete data
1336        // loss.
1337        //
1338        // Specifically, this method works as follows:
1339        // 1. detect defaultType
1340        // 2. prepare constants & variables for iteration
1341        // 3. iterate over mimeEntries:
1342        // 3.1 stop iteration if total number of mimeEntries reached typeOverallMax specified in
1343        //     DataKind
1344        // 3.2 replace unallowed types with defaultType
1345        // 3.3 check if the number of entries is below specificMax specified in AccountType
1346
1347        // Here, defaultType can be supplied in two ways
1348        // - via kind.defaultValues
1349        // - via kind.typeList.get(0).rawValue
1350        Integer defaultType = null;
1351        if (newDataKind.defaultValues != null) {
1352            defaultType = newDataKind.defaultValues.getAsInteger(COLUMN_FOR_TYPE);
1353        }
1354        final Set<Integer> allowedTypes = new HashSet<Integer>();
1355        // key: type, value: the number of entries allowed for the type (specificMax)
1356        final SparseIntArray typeSpecificMaxMap = new SparseIntArray();
1357        if (defaultType != null) {
1358            allowedTypes.add(defaultType);
1359            typeSpecificMaxMap.put(defaultType, -1);
1360        }
1361        // Note: typeList may be used in different purposes when defaultValues are specified.
1362        // Especially in IM, typeList contains available protocols (e.g. PROTOCOL_GOOGLE_TALK)
1363        // instead of "types" which we want to treate here (e.g. TYPE_HOME). So we don't add
1364        // anything other than defaultType into allowedTypes and typeSpecificMapMax.
1365        if (!Im.CONTENT_ITEM_TYPE.equals(newDataKind.mimeType) &&
1366                newDataKind.typeList != null && !newDataKind.typeList.isEmpty()) {
1367            for (EditType editType : newDataKind.typeList) {
1368                allowedTypes.add(editType.rawValue);
1369                typeSpecificMaxMap.put(editType.rawValue, editType.specificMax);
1370            }
1371            if (defaultType == null) {
1372                defaultType = newDataKind.typeList.get(0).rawValue;
1373            }
1374        }
1375
1376        if (defaultType == null) {
1377            Log.w(TAG, "Default type isn't available for mimetype " + newDataKind.mimeType);
1378        }
1379
1380        final int typeOverallMax = newDataKind.typeOverallMax;
1381
1382        // key: type, value: the number of current entries.
1383        final SparseIntArray currentEntryCount = new SparseIntArray();
1384        int totalCount = 0;
1385
1386        for (ValuesDelta entry : mimeEntries) {
1387            if (typeOverallMax != -1 && totalCount >= typeOverallMax) {
1388                break;
1389            }
1390
1391            final ContentValues values = entry.getAfter();
1392            if (values == null) {
1393                continue;
1394            }
1395
1396            final Integer oldType = entry.getAsInteger(COLUMN_FOR_TYPE);
1397            final Integer typeForNewAccount;
1398            if (!allowedTypes.contains(oldType)) {
1399                // The new account doesn't support the type.
1400                if (defaultType != null) {
1401                    typeForNewAccount = defaultType.intValue();
1402                    values.put(COLUMN_FOR_TYPE, defaultType.intValue());
1403                    if (oldType != null && oldType == TYPE_CUSTOM) {
1404                        values.remove(COLUMN_FOR_LABEL);
1405                    }
1406                } else {
1407                    typeForNewAccount = null;
1408                    values.remove(COLUMN_FOR_TYPE);
1409                }
1410            } else {
1411                typeForNewAccount = oldType;
1412            }
1413            if (typeForNewAccount != null) {
1414                final int specificMax = typeSpecificMaxMap.get(typeForNewAccount, 0);
1415                if (specificMax >= 0) {
1416                    final int currentCount = currentEntryCount.get(typeForNewAccount, 0);
1417                    if (currentCount >= specificMax) {
1418                        continue;
1419                    }
1420                    currentEntryCount.put(typeForNewAccount, currentCount + 1);
1421                }
1422            }
1423            newState.addEntry(ValuesDelta.fromAfter(values));
1424            totalCount++;
1425        }
1426    }
1427}
1428