/*-
 * ~~~~~~licensing~~~~~~
 * profile-runtime
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.profiles.runtime.impl;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.jline.utils.Log;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

import ru.entaxy.platform.profiles.runtime.Connector;
import ru.entaxy.platform.profiles.runtime.InConnector;
import ru.entaxy.platform.profiles.runtime.OutConnector;
import ru.entaxy.platform.profiles.runtime.SystemProfile;

public class SystemProfileImpl extends AbstractProfile implements SystemProfile {

	protected BundleContext bundleContext;
	
	protected ConnectorServiceTracker<InConnector> inConnectorsTracker;
	protected ConnectorServiceTracker<OutConnector> outConnectorsTracker;
	
	public void activate() {
		inConnectorsTracker = new ConnectorServiceTracker<>(InConnector.class);
		outConnectorsTracker = new ConnectorServiceTracker<>(OutConnector.class);
	}
	
	@Override
	public List<InConnector> getInConnectors() {
		return inConnectorsTracker.getServices();
	}

	@Override
	public List<OutConnector> getOutConnectors() {
		return outConnectorsTracker.getServices();
	}

	@Override
	public OutConnector getDefaultOutConnector() {
		// TODO implement
		return null;
	}

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

	protected class ConnectorServiceTracker<T extends Connector>{
		
		ServiceTracker<T, T> serviceTracker;
		
		Class<T> serviceClass;
		
		public ConnectorServiceTracker(Class<T> clazz) {
			
			this.serviceClass = clazz;
			
			try {
				
				Filter filter = createFilter(clazz);
				serviceTracker = new ServiceTracker<>(
						bundleContext
						, filter
						, new ConnectorServiceTrackerCustomizer<T>());
				serviceTracker.open(true);
				
			} catch (Exception e) {
				Log.error("Error creating service tracker for [" + SystemProfileImpl.this.getId() + "]", e);
			}
		}
		
		protected Filter createFilter(Class<T> clazz) throws InvalidSyntaxException {
			return SystemProfileImpl.this.bundleContext.createFilter(
					
				String.format("(&(%s=%s)(system=%s))"
						, Constants.OBJECTCLASS
						, clazz.getName()
						, SystemProfileImpl.this.getId())	
					);
		}
		
		public List<T> getServices(){
			if (serviceTracker.getServices() == null)
				return Collections.emptyList();
			return Arrays.asList((Object[])serviceTracker.getServices())
					.stream().map(service->(T)service)
					.collect(Collectors.toList());
		}
		
	}
	
	protected class ConnectorServiceTrackerCustomizer<T extends Connector> implements ServiceTrackerCustomizer<T, T>{

		protected Map<String, T> storage = new LinkedHashMap<>();
		
		@Override
		synchronized public T addingService(ServiceReference<T> reference) {
			T service = SystemProfileImpl.this.bundleContext.getService(reference);
			synchronized (storage) {
				storage.put(service.getId(), service);
			}
			return service;
		}

		@Override
		synchronized public void modifiedService(ServiceReference<T> reference, T service) {
			// TODO Auto-generated method stub
			
		}

		@Override
		synchronized public void removedService(ServiceReference<T> reference, T service) {
			synchronized (storage) {
				storage.remove(service.getId());
			}	
		}
		
	}
}
