package info.elexis.server.core.connector.elexis.internal;

import java.util.Optional;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import ch.elexis.core.common.DBConnection;
import ch.elexis.core.services.IElexisDataSource;
import ch.elexis.core.utils.CoreUtil;
import ch.elexis.core.utils.OsgiServiceUtil;
import info.elexis.server.core.connector.elexis.common.ElexisDBConnectionUtil;
import info.elexis.server.core.contrib.ApplicationShutdownRegistrar;
import info.elexis.server.core.contrib.IApplicationShutdownListener;

public class Activator implements BundleActivator {
	
	public static final String BUNDLE_ID = "info.elexis.server.core.connector.elexis";
	
	private static BundleContext context;
	private static IApplicationShutdownListener iasl = new ApplicationShutdownListener();
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.
	 * BundleContext)
	 */
	public void start(BundleContext bundleContext) throws Exception{
		Activator.context = bundleContext;
		
		Optional<IElexisDataSource> datasource = OsgiServiceUtil.getService(IElexisDataSource.class);
		
		if (!CoreUtil.isTestMode()) {
			Optional<DBConnection> connection = ElexisDBConnectionUtil.getConnection();
			if (connection.isPresent()) {
				datasource.get().setDBConnection(connection.get());
			}
		} 

		ApplicationShutdownRegistrar.addShutdownListener(iasl);
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception{
		ApplicationShutdownRegistrar.removeShutdownListener(iasl);
		
		Activator.context = null;
	}
	
	public static BundleContext getContext(){
		return context;
	}
	
}

@@ -164,16 +164,48 @@
 Context;
+%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -317,22 +317,27 @@
 ore.
-utils.CoreUtil
+status.ObjectStatus
 ;%0Aim
@@ -1134,17 +1134,20 @@
 source =
- 
+%0A%09%09%09
 OsgiServ
@@ -1197,42 +1197,94 @@
 ;%0A%09%09
-%0A%09%09if (!CoreUtil.isTestMode()) %7B%0A%09
+ObjectStatus currentConnectionStatus = datasource.get().getCurrentConnectionStatus();%0A
 %09%09Op
@@ -1307,16 +1307,22 @@
 ion%3E con
+figCon
 nection 
@@ -1369,16 +1369,18 @@
 ;%0A%09%09
+%0A%09
 %09if (con
 nect
@@ -1371,24 +1371,30 @@
 %09%09%0A%09%09if (con
+figCon
 nection.isPr
@@ -1404,16 +1404,58 @@
 nt()) %7B%0A
+%09%09%09if (currentConnectionStatus == null) %7B%0A
 %09%09%09%09data
@@ -1486,16 +1486,22 @@
 tion(con
+figCon
 nection.
@@ -1516,14 +1516,192 @@
 %09%09%09%7D
+ else %7B%0A%09%09%09%09LoggerFactory.getLogger(getClass()).warn(%0A%09%09%09%09%09%22DB Connection already provided %5B%7B%7D%5D, will NOT initialize via xml file%22,%0A%09%09%09%09%09currentConnectionStatus.getCode());%0A%09%09%09%7D%0A%09%09%7D
 %0A%09%09
-%7D %0A
 %0A%09%09A

Unify db connection order (test, env, config)