package com.example.mobilesafer.activity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mobilesafer.R;
import com.example.mobilesafer.adapter.MyBaseAdapter;
import com.example.mobilesafer.bean.BlackNumberInfo;
import com.example.mobilesafer.db.dao.BlackNumberDao;

public class CallSafeActivity extends Activity {
	private ListView blackList;
	private LinearLayout pbLayout;
	private List<BlackNumberInfo> blacknumberinfos;
	private int mPageSize = 20;
	private BlackNumberDao dao;
	// ×ÜµÄÒ³Êý
	private MyAdapter adapter;
	// ×îºóÒ»ÌõµÄ½Ç±ê
	int lastNumber;
	int offset = 0;

	// ´¦ÀíÐÅÏ¢
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pbLayout.setVisibility(View.GONE);
			if (adapter == null) {
				adapter = new MyAdapter(blacknumberinfos, CallSafeActivity.this);
				blackList.setAdapter(adapter);
			} else {
				adapter.notifyDataSetChanged();
			}
			
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_call_safe);

		dao = new BlackNumberDao(CallSafeActivity.this);
		initUI();
		initData();

	}

	/**
	 * ³õÊ¼»¯Êý¾Ý ÒòÎªÊÇÒ»¸öºÄÊ±²Ù×÷ËùÒÔ½«Æä·Åµ½×ÓÏß³ÌÖÐ½øÐÐ
	 */
	private void initData() {
		pbLayout.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				// Ë¯Ãß3ÃëÄ£·ÂÊý¾ÝÏÂÔØ
				// SystemClock.sleep(3000);

				if (blacknumberinfos == null) {
					blacknumberinfos = dao.findPar1(offset, mPageSize);
				} else {
					blacknumberinfos.addAll(dao.findPar1(offset, mPageSize));
				}
				// ¸ü¸Ä½Ç±ê£¬Ä¿µÄÊÇ±íÊ¾ÏÖÔÚÕû¸ölistviewÖÐÓÐ¶àÉÙÊý¾Ý£¬·½±ã±ß½çÅÐ¶¨
				offset = blacknumberinfos.size();
				System.out.println("offset is " + offset);
				handler.sendEmptyMessage(0);
			};
		}.start();
	}

	/**
	 * ³õÊ¼»¯UI
	 */
	private void initUI() {
		blackList = (ListView) findViewById(R.id.lv_black);
		pbLayout = (LinearLayout) findViewById(R.id.pb_layout);

		// Ìí¼Ó»¬¶¯¼àÌý
		blackList.setOnScrollListener(new OnScrollListener() {

			// µ±»¬¶¯Í£Ö¹µÄÊ±ºò
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lastNumber = blackList.getLastVisiblePosition();
				System.out.println(lastNumber);
				// ÅÐ¶Ï
				if (lastNumber == offset - 1) {
					// Îª×îºóÒ»Ìõ
					if (offset == dao.countNumber()) {
						// Ã»ÓÐÊý¾ÝÁË
						Toast.makeText(CallSafeActivity.this, "ÒÑ¾­ÊÇ×îºóÒ»ÌõÁË",
								Toast.LENGTH_SHORT).show();
						;
						return;
					}
					initData();
				}
			}

			// µ±ÕýÔÚ»¬¶¯µÄÊ±ºò
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
	}

	/**
	 * Ìí¼ÓºÚÃûµ¥ µ¥»÷ÊÂ¼þ
	 */
	public void addBlackNumber(View view) {
		AlertDialog.Builder dbuiler = new AlertDialog.Builder(this);
		final AlertDialog alertDialog = dbuiler.create();

		View dialog_add_blacknumber = View.inflate(this,
				R.layout.dialog_add_blacknumber, null);

		// »ñÈ¡×é¼þ
		Button bt_cancel = (Button) dialog_add_blacknumber
				.findViewById(R.id.bt_cancel);
		Button bt_commit = (Button) dialog_add_blacknumber
				.findViewById(R.id.bt_commit);
		final CheckBox cb_mode_phone = (CheckBox) dialog_add_blacknumber
				.findViewById(R.id.cb_mode_phone);
		final CheckBox cb_mode_sms = (CheckBox) dialog_add_blacknumber
				.findViewById(R.id.cb_mode_sms);
		final EditText et_add_number = (EditText) dialog_add_blacknumber
				.findViewById(R.id.et_add_number);

		/*
		 * Ìí¼ÓºÚÃûµ¥
		 */
		bt_commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// »ñÈ¡ÓÃ»§ÌîÐ´µÄÊý¾Ý
				String number = et_add_number.getText().toString();
				if (TextUtils.isEmpty(number)) {
					Toast.makeText(CallSafeActivity.this, "ÇëÌîÐ´ºÅÂë",
							Toast.LENGTH_SHORT).show();
					return;
				}
				String mode = "";
				if (cb_mode_phone.isChecked() && cb_mode_sms.isChecked()) {
					mode = "1";
				} else if (cb_mode_phone.isChecked()) {
					mode = "2";
				} else if (cb_mode_sms.isChecked()) {
					mode = "3";
				} else {
					Toast.makeText(CallSafeActivity.this, "Çë¹´Ñ¡À¹½ØÄ£Ê½",
							Toast.LENGTH_SHORT).show();
					return;
				}

				// Ìí¼Óµ½Êý¾Ý¿â
				boolean flag = dao.add(number, mode);
				if (!flag) {
					Toast.makeText(CallSafeActivity.this, "Ìí¼Óµ½Êý¾Ý¿âÊ§°Ü ",
							Toast.LENGTH_SHORT).show();
				}
				// ¸üÐÂUI
				BlackNumberInfo info = new BlackNumberInfo();
				info.setNumber(number);
				info.setMode(mode);

				blacknumberinfos.add(0, info);
				adapter.notifyDataSetChanged();
				alertDialog.dismiss();
			}
		});
		/*
		 * È¡Ïû
		 */
		bt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				return;
			}
		});

		alertDialog.setView(dialog_add_blacknumber);
		alertDialog.show();
	}

	class MyAdapter extends MyBaseAdapter<BlackNumberInfo> {
		// ³õÊ¼»¯
		public MyAdapter(List<BlackNumberInfo> list, Context context) {
			super(list, context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = new ViewHolder();
			if (convertView == null) {
				convertView = View.inflate(CallSafeActivity.this,
						R.layout.item_safe_call, null);
				holder.tvNumber = (TextView) convertView
						.findViewById(R.id.tv_number);
				holder.tvMode = (TextView) convertView
						.findViewById(R.id.tv_mode);
				holder.ivDelete = (ImageView) convertView
						.findViewById(R.id.iv_delete);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.tvNumber.setText(blacknumberinfos.get(position).getNumber());

			// »ñÈ¡µ½µ±Ç°¶ÔÏó
			final BlackNumberInfo info = list.get(position);
			// ¸øÉ¾³ýÌí¼Ó¼àÌý
			holder.ivDelete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String number = info.getNumber();
					boolean flag = dao.delete(number);
					if (flag) {
						Toast.makeText(CallSafeActivity.this, "É¾³ý³É¹¦",
								Toast.LENGTH_SHORT).show();
						// ÒÆ³ýÊý¾Ý£¬¸üÐÂUI
						list.remove(info);
						adapter.notifyDataSetChanged();
					} else {
						Toast.makeText(CallSafeActivity.this, "É¾³ýÊ§°Ü",
								Toast.LENGTH_SHORT).show();
					}
				}
			});

			String mode = blacknumberinfos.get(position).getMode();
			if (mode.equals("1")) {
				holder.tvMode.setText("µç»°+¶ÌÐÅÀ¹½Ø");
			} else if (mode.equals("2")) {
				holder.tvMode.setText("µç»°À¹½Ø");
			} else if (mode.equals("3")) {
				holder.tvMode.setText("¶ÌÐÅÀ¹½Ø");
			}
			return convertView;
		}
	}

	static class ViewHolder {
		TextView tvNumber;
		
		TextView tvMode;
		ImageView ivDelete;
	}
}
