/* 
 * Copyright 2012 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.service;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;

/**
 * Activity to start outgoing calls
 */
public class OutgoingCallActivity extends Activity
{
	private static final String ACTION_CALL_PRIVILEGED =
			"android.intent.action.CALL_PRIVILEGED";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
		if ((intent != null) &&
				(intent.getAction().equals(Intent.ACTION_CALL) ||
				intent.getAction().equals(ACTION_CALL_PRIVILEGED)))
		{
    		startService(new Intent(this, BoxService.class)
					.putExtra(BoxService.EXTRA_COMMAND,
							BoxService.Command.CALL.ordinal())
					.putExtra(BoxService.EXTRA_NUMBER,
							PhoneNumberUtils.getNumberFromIntent(
									intent, this))
					.putExtra(BoxService.EXTRA_FRITZ_APP,
							intent.getBooleanExtra(
									BoxService.EXTRA_FRITZ_APP, false)));
    		setResult(Activity.RESULT_OK);
		}
		else  setResult(Activity.RESULT_CANCELED);
		
		finish();
	}
	
	public static Intent createCallIntent(String number)
	{
		// emergency calls cannot be invoked by ACTION_CALL!
		String action = (PhoneNumberUtils.isEmergencyNumber(number)) ?
				Intent.ACTION_DIAL : Intent.ACTION_CALL;
		
		// escape and filter
		number = number.replace("+", "%2b").replace("#", "%23").replace("*", "%2a");
		
		return new Intent(action, Uri.parse("tel:" + number))
				.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
				.putExtra(BoxService.EXTRA_FRITZ_APP, true);
	}
}
