/*
 * 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;//调用android自带的类
import android.database.Cursor;//从数据库中导入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";//定义字符串常量

    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 = '+')";//定义字符串，匹配联系人

    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));//将CALLER_ID_SELECTION的最后的+好替代为号码的后MIN_MATCH位
        Cursor cursor = context.getContentResolver().query(//从数据库中读取数据
                Data.CONTENT_URI,
                new String [] { Phone.DISPLAY_NAME },//返回联系人姓名
                selection,
                new String[] { phoneNumber },
                null);//判断查询结果，move ToFirst返回第一条

        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();
            }
        } else {
            Log.d(TAG, "No contact matched with number:" + phoneNumber);//未匹配到该号码
            return null;
        }
    }
}
