/* 
 * 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 android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

import de.avm.fundamentals.logger.FileLog;

/**
 * Receiver for alarm broadcasts
 */
public class KeepAliveAlarm extends BroadcastReceiver
{
	private static final String TAG = "KeepAliveAlarm";
	
	/**
	 * Sets alarm for SIP keep alive to BoxService
	 * 
	 * @param context
	 * 		valid context
	 * @param delay
	 * 		delay time in seconds, 0 for cancel
	 */
	public static void setAlarm(Context context, int delay)
	{
    	FileLog.d(TAG, "setAlarm(" + delay + ")");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
        		new Intent(context, KeepAliveAlarm.class), 0);
		AlarmManager alarmManager = (AlarmManager)context
				.getSystemService(Context.ALARM_SERVICE);
		try
		{
			alarmManager.cancel(pendingIntent);
		}
		catch(Exception e)
		{
			// ignore, rare cases of NullPointerException if nothing
			// to cancel (according to market crash reports)
		}
		if (delay > 0)
			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
					SystemClock.elapsedRealtime() + delay * 1000, pendingIntent);
	}
	
	@Override
	public void onReceive(Context context, Intent intent)
	{
    	FileLog.d(TAG, "onReceive()");
		context.startService(new Intent(context, BoxService.class)
				.putExtra(BoxService.EXTRA_COMMAND,
						BoxService.Command.SIP_KEEPALIVE.ordinal()));
	}

}
