#include <mozilla-config.h>

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
#include "gecko.h"

#include <nsIServiceManager.h>
#include <nsIDirectoryService.h>
#include <nsIComponentRegistrar.h>
#include <nsIAppStartupNotifier.h>
#include <nsILocalFile.h>
#include <nsWidgetsCID.h>
#include <nsCOMPtr.h>
#include <nsIComponentManager.h>
#include <nsEmbedAPI.h>
#include <nsStringAPI.h>
#include <nsIAppShell.h>
#include <nsComponentManagerUtils.h>

static nsIServiceManager *sServiceManager = nsnull;
//static PRBool             sRegistryInitializedFlag = PR_FALSE;
static nsIDirectoryServiceProvider *sAppFileLocProvider = nsnull;
static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);

gboolean
gecko_init (void)
{
	nsresult rv;
	nsCOMPtr<nsILocalFile> binDir;

	rv = NS_NewNativeLocalFile (NS_LITERAL_CSTRING(MOZILLA_HOME), 1, getter_AddRefs(binDir));
	//rv = NS_NewNativeLocalFile (nsDependentCString(MOZILLA_HOME), 1, getter_AddRefs(binDir));
	if (NS_FAILED(rv)) return FALSE;

	rv = NS_InitXPCOM2 (&sServiceManager, binDir, sAppFileLocProvider);
	//NS_InitEmbedding (binDir, sAppFileLocProvider);

	nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(sServiceManager);
	NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
	registrar->AutoRegister(nsnull);
	nsIComponentManager *compMgr;
	rv = sServiceManager->QueryInterface (NS_GET_IID(nsIComponentManager),
			(void **) &compMgr);
	if (NS_FAILED(rv)) return FALSE;

	nsIObserver *startupNotifier;
	rv = compMgr->CreateInstanceByContractID (NS_APPSTARTUPNOTIFIER_CONTRACTID,
			NULL,
			NS_GET_IID(nsIObserver),
			(void **) &startupNotifier);
	if (NS_FAILED(rv)) return FALSE;

	NS_RELEASE (compMgr);

	nsCOMPtr<nsIAppShell> appShell;
	appShell = do_CreateInstance(kAppShellCID);
	if (!appShell)
	{
		NS_WARNING("Failed to create appshell");
		return FALSE;
	}
	appShell->Create(0, nsnull);
	appShell->Spinup();

	return NS_FAILED(rv) ? FALSE : TRUE;
}

gboolean
gecko_term (void)
{
	NS_IF_RELEASE (sServiceManager);

	return TRUE;
}


