package com.lyq.autocall;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	SharedPreferences sharedPreferences;//保存输入过的号码
	EditText edt1, edt2;
	TextView tv1, tv2;
	Button btn1, btn2, btn3;
	Thread thread;
	int repeatCount = 0;
	int amount;
	String number, tag = "MainActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edt1 = (EditText) findViewById(R.id.edittext1);
		edt2 = (EditText) findViewById(R.id.edittext2);
		tv1 = (TextView) findViewById(R.id.textview1);
		tv2 = (TextView) findViewById(R.id.textview2);
		btn1 = (Button) findViewById(R.id.button1);
		btn2 = (Button) findViewById(R.id.button2);
		btn3 = (Button) findViewById(R.id.button3);
		//声明一个优先级设置 类型，载入配置文件
		sharedPreferences = getSharedPreferences("phones", MODE_PRIVATE);
		edt1.setText(sharedPreferences.getString("number", ""));
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				if (edt1.getText().toString().trim().length() > 5
						&& edt2.getText().toString().trim().length() > 0) {
					//如果输入的是电话号码，则拨打
					number = edt1.getText().toString().trim();
					Editor editor = sharedPreferences.edit();
					editor.putString("number", number);
					editor.commit();
					//getString()第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
					Toast.makeText(getApplicationContext(),
							"AutoCall现在带您去挂断重拨", Toast.LENGTH_SHORT).show();
					amount = Integer.parseInt(edt2.getText().toString().trim());
					end2doCall();
				} else if (edt1.getText().toString().trim().length() <= 5) {
					//不拨打，提示输入号码错误
					Toast.makeText(getApplicationContext(),
							"检测到输入的非手机号码，傻眼了吧？", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(), "亲，至少拨打一次呀！",
							Toast.LENGTH_SHORT).show();
				}

			}
		});
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				if (edt1.getText().toString().trim().length() > 5
						&& edt2.getText().toString().trim().length() > 0) {
					//如果输入的是电话号码，则拨打
					number = edt1.getText().toString().trim();
					Editor editor = sharedPreferences.edit();
					editor.putString("number", number);
					editor.commit();
					//getString()第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
					amount = Integer.parseInt(edt2.getText().toString().trim());
					if (thread == null) {
						Toast.makeText(getApplicationContext(),
								"AutoCall现在带您去自动重拨", Toast.LENGTH_SHORT).show();
						thread = new Thread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								handler.sendEmptyMessage(0);
							}
						});
						thread.start();
						Log.i(tag, "thread started");
					} else {
						Toast.makeText(getApplicationContext(), "您正在拨打电话呢！",
								Toast.LENGTH_SHORT).show();
					}
					//					autoCall();
				} else if (edt1.getText().toString().trim().length() <= 5) {
					//不拨打，提示输入号码错误
					Toast.makeText(getApplicationContext(),
							"检测到输入的非手机号码，傻眼了吧？", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(), "亲，至少拨打一次呀！",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		btn3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				Toast.makeText(getApplicationContext(), "现在停止自动重拨！",
						Toast.LENGTH_SHORT).show();
				StopThread();
				MainActivity.this.finish();
			}
		});

	}

	protected void end2doCall() {
		// TODO 自动生成的方法存根

	}

	Handler handler = new Handler() {

		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (repeatCount >= amount) {
				StopThread();
				tv2.setText("已拨打次数：\n" + repeatCount + "次");

			} else {
				RepeatDial();
				tv2.setText("已拨打次数：\n" + repeatCount + "次");
			}
		}
	};

	private void RepeatDial() {
		MyPhoneStateListener myPhoneStateListener = new MyPhoneStateListener();//新建一个打电话监听器对象
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);//新建一个电环管理对象
		telephonyManager.listen(myPhoneStateListener,
				PhoneStateListener.LISTEN_CALL_STATE);
	}

	public class MyPhoneStateListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String phoneNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				if (repeatCount <= amount && thread != null) {
					repeatCount++;
					Intent intent = new Intent(Intent.ACTION_CALL,
							Uri.parse("tel:" + number));
					startActivity(intent);

					Toast.makeText(MainActivity.this, "正在拨打电话…",
							Toast.LENGTH_LONG).show();
				} else {
					StopThread();
				}
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 免提
	 * 
	 * @param context
	 */
	public void toggleSpeaker(Context context) {
		AudioManager am = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		am.setMode(AudioManager.MODE_IN_CALL);
		am.setSpeakerphoneOn(!am.isSpeakerphoneOn());
	}

	private void StopThread() {
		if (thread != null) {
			//需要调用停止线程的interrupt()方法，因为线程有可能在wait()或sleep(), 提高停止线程的即时性
			thread.interrupt();
			//不建议使用			thread.stop();
			thread = null;
			Log.i(tag, "thread stoped");
		}
	}

	public void autoCall() {
		//传入服务， parse（）解析号码
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
				+ number));
		//通知activtity处理传入的call服务
		MainActivity.this.startActivity(intent);
	}

}
