package com.zhn.tongxunlu;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.zhn.tongxunlu.R.id;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	Context mContext = null;

	/** 获取库Phon表字段 **/
	private static final String[] PHONES_PROJECTION = new String[] {
			Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
	/** 联系人显示名称 **/
	private static final int PHONES_DISPLAY_NAME_INDEX = 0;
	/** 电话号码 **/
	private static final int PHONES_NUMBER_INDEX = 1;
	/** 头像ID **/
	private static final int PHONES_PHOTO_ID_INDEX = 2;
	/** 联系人的ID **/
	private static final int PHONES_CONTACT_ID_INDEX = 3;

	List<Contact> contacts = new ArrayList<Contact>();
	ContactAdapter adapter;
	ListView listper;
	private PopupWindow popupWindow;
	TextView tvCall, tvMsg, tvEdit, tvDelete;
	ImageView addContacts;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		mContext = this;
		getPhoneContacts();
		listper = (ListView) findViewById(R.id.contactsListView);
		addContacts = (ImageView) findViewById(R.id.addPerson);
		adapter = new ContactAdapter(mContext, contacts, listper);
		listper.setAdapter(adapter);

		/* 添加联系人 */
		addContacts.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, AddpersonActivity.class);
				startActivityForResult(intent, 0);
			}
		});

		listper.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, final int pos,
					long arg3) {
				View popupwindow_view = getLayoutInflater().inflate(
						R.layout.popwindow_item, null, false);
				popupWindow = new PopupWindow(popupwindow_view, 400,
						LayoutParams.WRAP_CONTENT, true);
				popupWindow.setFocusable(true);
				ColorDrawable dw = new ColorDrawable(0xb0000000);
				popupWindow.setBackgroundDrawable(dw);
				popupWindow.setAnimationStyle(R.style.Animi);
				popupWindow.showAtLocation(v, Gravity.CENTER,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				popupWindow.setOnDismissListener(new poponDismissListener());
				backgroundAlpha((float) 0.5);

				/* 拨打电话 */
				tvCall = (TextView) popupwindow_view.findViewById(R.id.call);
				tvCall.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri
								.parse("tel:" + contacts.get(pos).getPhone()));
						startActivity(dialIntent);
					}
				});
				/* 发送短信 */
				tvMsg = (TextView) popupwindow_view.findViewById(R.id.sim);
				tvMsg.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setType("vnd.android-dir/mms-sms");
						intent.setData(Uri
								.parse("content://mms-sms/conversations/" + 1));// 此为号码
						startActivity(intent);
					}
				});

				/* 编辑信息 */
				tvEdit = (TextView) popupwindow_view.findViewById(R.id.edit);
				tvEdit.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Contact c = new Contact();
						c.setName(contacts.get(pos).getName());
						c.setPhone(contacts.get(pos).getPhone());

						Intent intent = new Intent(mContext, EditActivity.class);
						intent.putExtra("Person_info", c);
						startActivity(intent);
						popupWindow.dismiss();
					}
				});

				/* 删除联系人 */
				tvDelete = (TextView) popupwindow_view
						.findViewById(R.id.delete);
				tvDelete.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						try {
							deletePer();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						adapter.notifyDataSetChanged();
					}

					private void deletePer() throws Exception {
						String name = contacts.get(pos).getName();
						// 根据姓名求id
						Uri uri = Uri
								.parse("content://com.android.contacts/raw_contacts");
						ContentResolver resolver = mContext
								.getContentResolver();
						Cursor cursor = resolver.query(uri,
								new String[] { Data._ID }, "display_name=?",
								new String[] { name }, null);
						if (cursor.moveToFirst()) {
							int id = cursor.getInt(0);
							resolver.delete(uri, "display_name=?",
									new String[] { name });
							uri = Uri
									.parse("content://com.android.contacts/data");
							resolver.delete(uri, "raw_contact_id=?",
									new String[] { id + "" });
						}
						contacts.remove(pos);
						popupWindow.dismiss();
					}
				});

				popupwindow_view.setOnTouchListener(new OnTouchListener() {

					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if (popupWindow != null && popupWindow.isShowing()) {
							popupWindow.dismiss();
							popupWindow = null;
						}
						return false;
					}
				});
			}
		});
	}

	public void backgroundAlpha(float bgAlpha) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = bgAlpha;
		getWindow().setAttributes(lp);
	}

	// 获取手机联系人
	private void getPhoneContacts() {
		ContentResolver resolver = mContext.getContentResolver();
		Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
				PHONES_PROJECTION, null, null, null);
		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				if (TextUtils.isEmpty(phoneNumber))
					continue;
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);
				Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
				Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
				Bitmap contactPhoto = null;
				if (photoid > 0) {
					Uri uri = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI, contactid);
					InputStream input = ContactsContract.Contacts
							.openContactPhotoInputStream(resolver, uri);
					contactPhoto = BitmapFactory.decodeStream(input);
				} else {
					contactPhoto = BitmapFactory.decodeResource(getResources(),
							R.drawable.preson_icon);
				}
				Contact contact = new Contact();
				contact.setName(contactName);
				contact.setPhone(phoneNumber);
				contact.setPhotoId(contactPhoto);
				contacts.add(contact);
			}
			phoneCursor.close();
		}
	}

	// 获取Sims卡联系人
	private void getSIMContacts() {
		ContentResolver resolver = mContext.getContentResolver();
		Uri uri = Uri.parse("content://icc/adn");
		Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
				null);

		if (phoneCursor != null) {
			while (phoneCursor.moveToNext()) {
				String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
				if (TextUtils.isEmpty(phoneNumber))
					continue;
				String contactName = phoneCursor
						.getString(PHONES_DISPLAY_NAME_INDEX);

				Contact contact = new Contact();
				contact.setName(contactName);
				contact.setPhone(phoneNumber);
				contacts.add(contact);
			}
			phoneCursor.close();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == 0) {
			if (data != null) {
				Bundle bundleData = data.getExtras();
				Contact contact = (Contact) bundleData
						.getSerializable("contact");
				contacts.add(contact);
				Toast.makeText(mContext, "添加成功", 1).show();
				String name = contact.getName();
				String phone = contact.getPhone();
				Log.i("name++++++++++++++++++++++++++++++++++", name);
				Log.i("phone+++++++++++++++++++++++++++++++++", phone);
				/* 添加联系人数据库操作 */
				ContentValues cv = new ContentValues();
				ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
				ContentProviderOperation.Builder builder = ContentProviderOperation
						.newInsert(RawContacts.CONTENT_URI);
				builder.withValues(cv);
				operationList.add(builder.build());
				builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
				builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0);
				builder.withValue(Data.MIMETYPE,
						StructuredName.CONTENT_ITEM_TYPE);
				builder.withValue(StructuredName.DISPLAY_NAME, name);
				operationList.add(builder.build());
				builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
				builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0);
				builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
				builder.withValue(Phone.NUMBER, phone);
				builder.withValue(Data.IS_PRIMARY, 1);
				operationList.add(builder.build());
				try {
					getContentResolver().applyBatch(ContactsContract.AUTHORITY,
							operationList);
				} catch (RemoteException e) {
					e.printStackTrace();
				} catch (OperationApplicationException e) {
					e.printStackTrace();
				}
			}else {
				Toast.makeText(getApplicationContext(), "亲，你还未添加信息哦！", 1).show();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	class poponDismissListener implements PopupWindow.OnDismissListener {

		@Override
		public void onDismiss() {
			// TODO Auto-generated method stub
			// Log.v("List_noteTypeActivity:", "我是关闭事件");
			backgroundAlpha(1f);
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		adapter.notifyDataSetChanged();
		super.onResume();
	}

}
