/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.data;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;

import java.util.HashMap;

public static String getContact(Context context, String phoneNumber) {
    if(sContactCache == null) { //如果缓存为空则创建一个新的 HashMap
        sContactCache = new HashMap<String, String>();
    }

    if(sContactCache.containsKey(phoneNumber)) { //如果缓存中已存在对应的电话号码则返回其对应的联系人姓名
        return sContactCache.get(phoneNumber);
    }

    //否则根据电话号码查询联系人姓名
    String selection = CALLER_ID_SELECTION.replace("+",
            PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); //将 "+" 替换为待查询电话号码的最小完全匹配
    Cursor cursor = context.getContentResolver().query(
            Data.CONTENT_URI, //uri为ContentProvider提供的数据查询接口的位置(Data.CONTENT_URI)
            new String [] { Phone.DISPLAY_NAME }, //需要查询的数据项，查询联系人姓名
            selection, //查询条件
            new String[] { phoneNumber }, //占位符对应的实际参数
            null); //排序方式为空

    if (cursor != null && cursor.moveToFirst()) { //如果查询结果非空，获取查询结果中的第一条记录
        try {
            String name = cursor.getString(0); //获取联系人姓名
            sContactCache.put(phoneNumber, name); //将电话号码及其联系人姓名加入 HashMap 缓存中
            return name; //返回联系人姓名
        } catch (IndexOutOfBoundsException e) { //处理异常
            Log.e(TAG, " Cursor get string error " + e.toString());
            return null; //返回null
        } finally {
            cursor.close(); //释放cursor
        }
    } else { //如果返回为空，打印调试信息并返回null
        Log.d(TAG, "No contact matched with number:" + phoneNumber);
        return null; //返回null
    }
}
