package gr.mybook.mycall;

import gr.mybook.mycall.R;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
  EditText number;
  Button btn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		number = (EditText) findViewById(R.id.editText1);
		btn = (Button) findViewById(R.id.button1);
		// add PhoneStateListener
		PhoneCallListener phoneListener = new PhoneCallListener();
		TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
	}
	
	public void phoneCall(View v) {
		String numberToDial = "tel:" + number.getText().toString();
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(numberToDial));
		startActivity(intent);
	}
	
	// monitor phone call states
	private class PhoneCallListener extends PhoneStateListener {
		String TAG = "gr.mybook.mycall";
		private boolean isPhoneCalling = false;
		
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
		   if (TelephonyManager.CALL_STATE_RINGING == state) {
				// phone is ringing
				Log.i(TAG, "RINGING, number: " + incomingNumber);
		   }
			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				// phone is active
				Log.i(TAG, "OFFHOOK");
				isPhoneCalling = true;
			}
			if (TelephonyManager.CALL_STATE_IDLE == state) {
				// phone call ended, launch main activity
				Log.i(TAG, "IDLE");
				if (isPhoneCalling) {
					Log.i(TAG, "restart app");
					// restart app
					Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
					isPhoneCalling = false;
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
