/*-
 * ~~~~~~licensing~~~~~~
 * datasources-initializer
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.platform.runtime.core.initializer.datasources;

import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.InitializerException;

import javax.sql.DataSource;
import java.util.Collection;

public class DataSourcesInitializer extends AbstractInitializer {

	protected static final Logger log = LoggerFactory.getLogger(DataSourcesInitializer.class);
	
	protected static Initializer.Callback callback = null;
	
	public static void collectorCompleted() {
		if (DataSourcesInitializer.callback != null)
			DataSourcesInitializer.callback.inited(new DataSourcesInitializer());
	}
	
	@Override
	public void init() throws InitializerException {
		log.info("Init in DataSourcesInitializer is called");
		try {
			Collection<ServiceReference<DataSource>> dataSources = 
					this.bundleContext.getServiceReferences(
					javax.sql.DataSource.class, 
					"(|(osgi.jndi.service.name=entaxy.esb.storage)(osgi.jndi.service.name=entaxy.esb.cache))");
			if (dataSources.size()!=2)
				throw new InitializerException(this, "Datasources initialization error", "Datasources count = " + dataSources.size(), null);
		} catch (InvalidSyntaxException e) {
			e.printStackTrace();
			log.error("Initializer error: " + e.getMessage());
			throw new InitializerException(this, "Initializer exception", "Initializer exception", e);
		}
	}

	@Override
	public void reinit() throws InitializerException {
		log.info("ReInit in CoreInitializer is called");
	}
	
	@Override
	public void setCalllback(Callback callback) {
		DataSourcesInitializer.callback = callback;
	}
}
