/*
 * 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 class Contact {
     // 静态缓存，用于存储电话号码与对应联系人名称的映射关系，避免重复查询数据库
    private static HashMap<String, String> sContactCache;
     // 日志标签
    private static final String TAG = "Contact";
    // 查询条件模板：
    // 1. 使用PHONE_NUMBERS_EQUAL比较电话号码（考虑格式差异）
    // 2. 数据类型为电话条目
    // 3. 限制raw_contact_id必须在phone_lookup表中匹配指定最小匹配长度的记录
    private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
    + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
    + " AND " + Data.RAW_CONTACT_ID + " IN "
            + "(SELECT raw_contact_id "
            + " FROM phone_lookup"
            + " WHERE min_match = '+')";
     /**
     * 根据电话号码查询联系人名称
     * @param context    上下文对象，用于访问内容解析器
     * @param phoneNumber 要查询的电话号码
     * @return 联系人名称，如果未找到或出错则返回null
     */
    public static String getContact(Context context, String phoneNumber) {
    // 初始化缓存
        if(sContactCache == null) {
            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,// 访问组合联系人数据
                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);
                return name;
            } catch (IndexOutOfBoundsException e) {
                Log.e(TAG, " Cursor get string error " + e.toString());
                return null;
            } finally {
                cursor.close();// 确保关闭Cursor释放资源
            }
        } else {
            Log.d(TAG, "No contact matched with number:" + phoneNumber);
            return null;
        }
    }
}
