/* 
 * 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 de.avm.android.fritzapp.com.ComSettingsChecker;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

/**
 * Manages Lock depending on connection status
 */
public class ComLock
{
	private ConnectivityManager mConnectivityManager;
	private WifiManager mWifiManager;
	private WifiManager.WifiLock mWifiLock = null;
	
	public ComLock(Context context)
	{
		mConnectivityManager = (ConnectivityManager)context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mWifiManager = (WifiManager)context
				.getSystemService(Context.WIFI_SERVICE);
	}
	
	public void refresh()
	{
		// FIXME besser nur bei ComSettingsChecker.getSipState() == ComSettingsChecker.SIP_AVAILABLE?
		if (ComSettingsChecker.isConnected())
		{
			// using Wifi?
			NetworkInfo ni = mConnectivityManager.getActiveNetworkInfo();
			setWifiLock((ni != null) &&
					(ni.getType() == ConnectivityManager.TYPE_WIFI) &&
					ni.isConnectedOrConnecting());
		}
		else setWifiLock(false);
	}
	
	public void clear()
	{
		setWifiLock(false);
	}
	
	private void setWifiLock(boolean on)
	{
		if (on)
		{
			if (mWifiLock == null)
			{
				mWifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL,
						getClass().getName());
				mWifiLock.acquire();
			}
			else if (!mWifiLock.isHeld())
			{
				mWifiLock.acquire();
			}
		}
		else if ((mWifiLock != null) && mWifiLock.isHeld())
		{
			mWifiLock.release();
		}
	}
}
