/* 
 * Copyright 2015 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 de.avm.android.fritzapp.com.ComSettingsChecker;
import de.avm.android.fritzapp.gui.SettingsExtendedActivity;
import de.avm.android.fritzapp.sipua.ui.Sipdroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;

public class NewOutgoingCallReceiver extends BroadcastReceiver
{
	private static final String PREF_LASTCALL ="NewOutgoingCall";
	private static final long HOLD_LASTCALL_MILLIS = 10 * 1000;
	
	private static final String EXTRA_PHONE_ALREADY_CALLED =
			"android.phone.extra.ALREADY_CALLED";
    private static final String EXTRA_ORIGINAL_URI =
    		"android.phone.extra.ORIGINAL_URI";

    public static void ignore(Context context, Intent intent)
    {
		Uri uri = intent.getData();
    	String action = (intent == null) ? "" : intent.getAction();
    	if ((uri != null) &&
    			(action.equals(Intent.ACTION_CALL) ||
    					action.equals(Intent.ACTION_DIAL)) &&
				(SettingsExtendedActivity.isHtcIntegrationMode(context)))
    	{
    		Editor editor = PreferenceManager
    				.getDefaultSharedPreferences(context).edit();
    		editor.putString(PREF_LASTCALL,
    				Long.toString(System.currentTimeMillis()) + "\t" +
					uri.toString());
    		editor.apply();
    	}
    }
    
	@Override
	public void onReceive(Context context, Intent intent)
	{
		if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL) &&
				!intent.getBooleanExtra(EXTRA_PHONE_ALREADY_CALLED, false) &&
				Sipdroid.on(context) &&
				(ComSettingsChecker.getSipState() == ComSettingsChecker.SIP_AVAILABLE))
		{
			if (SettingsExtendedActivity.isHtcIntegrationMode(context))
			{
				String number = null;
				Uri uri = null;
				try { uri = Uri.parse(intent.getStringExtra(EXTRA_ORIGINAL_URI)); }
				catch(Exception e) {  }
				if (uri == null)
				{
			        number = getResultData();
			        if (TextUtils.isEmpty(number))
			        	number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
					try { uri = Uri.parse("tel:" + number); }
					catch(Exception e) {  }
				}
				
		        if ((uri != null) && !testFor2ndBc(context, uri))
		        {
	        		// ask for target app
					context.startActivity(new Intent(Intent.ACTION_CALL, uri)
							.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
					setResultData(null);
		        }
			}
		}
	}
	
	private boolean testFor2ndBc(Context context, Uri uri)
	{
		long currentMillis = System.currentTimeMillis();
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		String lastCall = prefs.getString(PREF_LASTCALL, null);
		
		try
		{
			if (!TextUtils.isEmpty(lastCall))
			{
				int pos = lastCall.indexOf('\t');
				if (pos > 0)
				{
					if ((Long.parseLong(lastCall.substring(0, pos)) +
							HOLD_LASTCALL_MILLIS) >= currentMillis)
					{
						if (uri.toString()
								.compareTo(lastCall.substring(pos + 1)) == 0);
						{
							lastCall = "";
							return true;
						}
					}
				}
			}
			
			lastCall = Long.toString(currentMillis) + "\t" +
					uri.toString();
		}
		catch(Exception e)
		{
			lastCall = Long.toString(currentMillis) + "\t" +
					uri.toString();
		}
		finally
		{
			Editor editor = prefs.edit();
			editor.putString(PREF_LASTCALL, lastCall);
			editor.apply();
		}

		return false;
	}
}
