/*-
 * ~~~~~~licensing~~~~~~
 * configuration-test-1
 * ==========
 * Copyright (C) 2020 - 2022 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.platform.base.config;

import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImmutablesImpl implements Immutables {

	private static final Logger log = LoggerFactory.getLogger(ImmutablesImpl.class);
	
	protected BundleContext bundleContext;
	
	protected String pid;
	protected Map<String, Object> properties;
	
	public ImmutablesImpl() {
		super();
	}

	public ImmutablesImpl(String pid, BundleContext bundleContext) {
		super();
		setPid(pid);
		setBundleContext(bundleContext);
	}

	public ImmutablesImpl(String pid, BundleContext bundleContext, Map<String, Object> properties) {
		super();
		setProperties(properties);
		setPid(pid);
		setBundleContext(bundleContext);
	}
	
	public void setPid(String pid) {
		this.pid = pid;
		checkAndRegister();
	}

	public void setProperties(Map<String, Object> properties) {
		this.properties = properties;
	}

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
		checkAndRegister();
	}

	protected void checkAndRegister() {
		if ((this.pid != null) && (this.bundleContext != null)) {
			
			log.debug("\n\tcheckAndRegister :: START");
			
			ServiceReference<ImmutablesCollector> collectorRef = this.bundleContext.getServiceReference(ImmutablesCollector.class);
			if (collectorRef != null) {
				log.debug("\n\tcheckAndRegister :: GET COLLECTOR");
				ImmutablesCollector collector = this.bundleContext.getService(collectorRef);
				if (collector != null)
					collector.add(this);
				else
					log.debug("\n\tcheckAndRegister :: COLLECTOR IS NULL");
				this.bundleContext.ungetService(collectorRef);
			} else {
				log.debug("\n\tcheckAndRegister :: REF IS NULL");
			}
		}
	}
	
	@Override
	public String getPid() {
		return this.pid;
	}

	@Override
	public Map<String, Object> getProperties() {
		return this.properties;
	}

}
