/* 
 * 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.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import de.avm.fundamentals.logger.FileLog;

public class BoxServiceConnection
		implements ServiceConnection, IBoxServiceListener
{
    private static final String TAG = "BoxServiceConnection";
	public void onBoxServiceConnected() {}
	public void onBoxServiceDisconnected() {}
	public void onBoxesSearchDone(Exception error) {}
	public void onComError(ComErrorMessage comError) {}
	
	public void onComStatusChanged() {}
	
	private Context mContext = null;
	private BoxService.Binder mBinder = null;
	
	public IBoxService getService()
	{
		return mBinder;
	}
	
	public boolean bindService(Context context)
	{
		if (mBinder != null) return true;
		if (context.bindService(new Intent(context, BoxService.class),
								this, Context.BIND_AUTO_CREATE))
		{
			mContext = context;
			return true;
		}
		return false;
	}

	public void unbindService()
	{
		if (mBinder != null)
		{
			mBinder.unregisterListener(this);
			mContext.unbindService(this);
			onServiceDisconnected(null); // not called from unbindService
		}
	}
	
	public void onServiceConnected(ComponentName name, IBinder service)
	{
		mBinder = (BoxService.Binder)service;
		mBinder.registerListener(this);
		try
        {
            onBoxServiceConnected();
        }
		catch(Exception e)
        {
            FileLog.w(TAG, e.getMessage(), e);
        }
	}

	public void onServiceDisconnected(ComponentName name)
	{
		if (mBinder != null)
		{
			mBinder = null;
			mContext = null;
			try
            {
                onBoxServiceDisconnected();
            }
            catch(Exception e)
            {
                FileLog.w(TAG, e.getMessage(), e);
            }
		}
	}
}
