package me.yoqi.deleteallcontacts.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;

/**
 * 联系人管理，三个表 ContactsContract.Data.CONTENT_URI;
 * ContactsContract.RawContacts.CONTENT_URI
 * ContactsContract.Contacts.CONTENT_URI
 * 
 * @author liuyuqi
 *
 */
public class ContactManager {
	ContentResolver resolver;
	static String TAG = "me.yoqi.deleteallcontacts.utils.ContactManager";

	public ContactManager(Context context) {
		resolver = context.getContentResolver();
	}

	/**
	 * 删除所有联系人
	 * 
	 * @return
	 */
	public HashMap<String, Object> delAllContacts() {
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		ContentProviderOperation op = null;
		Uri uri = null;
		HashMap<String, Object> delResult = new HashMap<String, Object>();
		int num = 0;// 删除影响的行数
		resolver.delete(
				Uri.parse(ContactsContract.RawContacts.CONTENT_URI.toString() + "?"
						+ ContactsContract.CALLER_IS_SYNCADAPTER + "=true"),
				ContactsContract.RawContacts._ID + ">0", null);
		// 删除Data表的数据
		uri = Uri.parse(Data.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
		op = ContentProviderOperation.newDelete(uri).withSelection(Data.RAW_CONTACT_ID + ">0", null)
				.withYieldAllowed(true).build();
		ops.add(op);
		// 删除RawContacts表的数据
		uri = Uri.parse(RawContacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
		op = ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts._ID + ">0", null)
				.withYieldAllowed(true).build();
		ops.add(op);
		// 删除Contacts表的数据
		uri = Uri.parse(Contacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
		op = ContentProviderOperation.newDelete(uri).withSelection(Contacts._ID + ">0", null).withYieldAllowed(true)
				.build();
		ops.add(op);
		// 执行批量删除
		try {
			ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);
			for (ContentProviderResult result : results) {
				num += result.count;
				Log.i(TAG, "删除影响的行数：" + result.count);
			}
			delResult.put("result", "1");
			delResult.put("obj", num);
		} catch (Exception e) {
			Log.i(TAG, e.getMessage());
			delResult.put("result", "-1");
			delResult.put("obj", "删除失败！" + e.getMessage());
		}
		if (delResult.size() == 0) {
			delResult.put("result", "0");
			delResult.put("obj", "无效删除，联系人信息不正确！");
		}
		return delResult;
	}

	/**
	 * 删除联系人 ，联系人相关联的有三张表，将三张表的数据全部删除 部分手机删除第二张即可，部分手机需要删除三张表
	 * resolver.delete(ContactsContract.Data.CONTENT_URI, null, null);
	 * resolver.delete(ContactsContract.RawContacts.CONTENT_URI, null, null);
	 * resolver.delete(ContactsContract.Contacts.CONTENT_URI, null, null);
	 * 
	 * @param contactId
	 *            联系人ID
	 * @param groupId
	 * @return 如果删除成功：(1, num); 如果删除失败：(-1, "删除失败:" + e.getMessage());
	 *         如果信息无效：(0, "无效删除，联系人信息不正确！");
	 */
	public HashMap<String, Object> delContacts(List<String> contactIds) {
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		ContentProviderOperation op = null;
		Uri uri = null;

		HashMap<String, Object> delResult = new HashMap<String, Object>();
		int num = 0;// 删除影响的行数
		if (Utils.isEmpty(contactIds)) {
			delResult.put("result", "0");
			delResult.put("obj", "无效删除，联系人id不正确！");
			return delResult;
		}
		List<String> ids = new ArrayList<String>();
		String selection = " in(";
		for (String contactId : contactIds) {
			// 如果联系人id 不大于 0,或者不存在，循环下一次
			if (!Utils.isNumber(contactId) || Long.parseLong(contactId) <= 0 || !isExistContact(contactId)) {
				continue;
			}
			selection += "?,";
			ids.add(contactId);
		}
		if (ids.size() == 0) {
			delResult.put("result", "0");
			delResult.put("obj", "无效联系人id");
			return delResult;
		}
		selection = selection.substring(0, selection.length() - 1) + ")";
		String[] selectionArgs = ids.toArray(new String[] {});

		// 删除Data表的数据
		uri = Uri.parse(Data.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
		op = ContentProviderOperation.newDelete(uri).withSelection(Data.RAW_CONTACT_ID + selection, selectionArgs)
				.withYieldAllowed(true).build();
		ops.add(op);
		// 删除RawContacts表的数据
		uri = Uri.parse(RawContacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
		op = ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
				.withSelection(RawContacts._ID + selection, selectionArgs).withYieldAllowed(true).build();
		ops.add(op);
		// 删除Contacts表的数据
		uri = Uri.parse(Contacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");
		op = ContentProviderOperation.newDelete(uri).withSelection(Contacts._ID + selection, selectionArgs)
				.withYieldAllowed(true).build();
		ops.add(op);

		// 执行批量删除
		try {
			ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);
			for (ContentProviderResult result : results) {
				num += result.count;
				Log.i(TAG, "删除影响的行数：" + result.count);
			}
			delResult.put("result", "1");
			delResult.put("obj", num);
		} catch (Exception e) {
			Log.i(TAG, e.getMessage());
			delResult.put("result", "-1");
			delResult.put("obj", "删除失败！" + e.getMessage());
		}
		if (delResult.size() == 0) {
			delResult.put("result", "0");
			delResult.put("obj", "无效删除，联系人id不正确！");
		}
		return delResult;
	}

	/**
	 * 根据id查询联系人是否存在
	 */
	private boolean isExistContact(String id) {
		if (Utils.isEmpty(id)) {
			return false;
		}
		Cursor cursor = resolver.query(Contacts.CONTENT_URI, new String[] { Contacts._ID }, Contacts._ID + " = ? ",
				new String[] { id }, null);

		if (cursor.moveToFirst()) {
			return true;
		}
		cursor.close();
		return false;
	}

	/**
	 * 根据组的 id 查询组是否存在
	 * 
	 * @return boolean
	 */
	public boolean isExistGroup(String id) {
		if (Utils.isEmpty(id)) {
			return false;
		}
		Cursor cursor = resolver.query(Groups.CONTENT_URI, new String[] { Groups._ID }, Groups._ID + "=" + id, null,
				null);
		if (cursor.moveToFirst()) {
			return true;
		}
		cursor.close();
		return false;
	}

	/**
	 * 查询所有联系人
	 */
	public ArrayList<String> getAllContact() {
		ArrayList<String> res = new ArrayList<String>();
		Uri uri = ContactsContract.Data.CONTENT_URI;
		Cursor cursorUser = resolver.query(uri,
				new String[] { ContactsContract.CommonDataKinds.Phone._ID,
						ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
						ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID },
				null, null, null);

		while (cursorUser.moveToNext()) {
			int id = cursorUser.getInt(0); // 按上面数组的声明顺序获取
			String name = cursorUser.getString(1);
			int rawContactsId = cursorUser.getInt(2);
			res.add("id:" + id + " ,name:" + name + " ,rawContacntsID:" + rawContactsId + "\r\n");
		}
		return res;
	}

}
