/**
 * 
 */
package com.beem.project.beem;

import com.beem.project.beem.service.aidl.IXMPPFacade;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.IBinder;

/**
 * @author darisk
 */
public class BeemApplication extends Application {

    private IXMPPFacade mFacade;
  
    private Context mApplicationContext;
    private Resources mPrivateResources;
    private static BeemApplication mBeemApp;
    
    public static BeemApplication getApplication(Activity activity) {
	if (mBeemApp == null) {
	    mBeemApp = new BeemApplication();
	    mBeemApp.mApplicationContext = activity.getApplication();
	    mBeemApp.mPrivateResources = activity.getResources();
	    mBeemApp.onCreate();
	}
	return mBeemApp;
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
	// TODO Auto-generated method stub
	super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreate() {
	// TODO Auto-generated method stub
	super.onCreate();
	mFacade = null;
    }

    @Override
    public void onLowMemory() {
	// TODO Auto-generated method stub
	super.onLowMemory();
    }

    @Override
    public void onTerminate() {
	// TODO Auto-generated method stub
	super.onTerminate();
    }

    public synchronized void startBeemService() {
	if (mFacade == null) {
	    // Intent intent = new Intent(this, BeemService.class);
	    Intent intent = new Intent();
	    intent.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
	    mApplicationContext.startService(intent);
	    mApplicationContext.bindService(intent, mServConn, BIND_AUTO_CREATE);
	}
    }

    private ServiceConnection mServConn = new ServiceConnection() {

	@Override
	public void onServiceDisconnected(ComponentName name) {
	    mFacade = null;

	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
	    mFacade = IXMPPFacade.Stub.asInterface(service);
	}
    };

    public synchronized void stopBeemService() {
	Intent intent = new Intent(this, BeemService.class);
	mApplicationContext.unbindService(mServConn);
	mApplicationContext.stopService(intent);
    }

    public IXMPPFacade getXmppFacade() {
	return mFacade;
    }

}
