/*-
 * ~~~~~~licensing~~~~~~
 * connection-producing
 * ==========
 * 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.base.objects.connection.producing.adapters;

import java.net.URL;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

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

import com.google.gson.JsonObject;

import ru.entaxy.base.generator.template.Template;
import ru.entaxy.base.generator.template.TemplateImpl;
import ru.entaxy.base.generator.template.TemplateService;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryUtils;
import ru.entaxy.platform.base.objects.factory.impl.DefaultFactory;
import ru.entaxy.platform.base.objects.factory.tracker.TrackedFactoryManager;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerCustomizerListener;

public class TrackedAdapterCustomizerListener implements BundleTrackerCustomizerListener<List<TrackedAdapter>> {

	private static final Logger log = LoggerFactory.getLogger(TrackedAdapterCustomizerListener.class);
	
	protected BundleContext bundleContext;
	
	protected TrackedFactoryManager trackedFactoryManager;
	
	public TrackedAdapterCustomizerListener(BundleContext bundleContext, TrackedFactoryManager factoryManager) {
		super();
		this.bundleContext = bundleContext;
		this.trackedFactoryManager = factoryManager;
	}
	
	@Override
	public void added(List<TrackedAdapter> managedObject) {
		
		for (TrackedAdapter adapter: managedObject) {

			// create factory
			
			AdapterWrapperDefaultFactory factory = new AdapterWrapperDefaultFactory();
			// factory.setFactoryId(adapter.getId());
			JsonObject effective = EntaxyFactoryUtils.calculateEffectiveJson(
					JSONUtils.getJsonRootObject(adapter.configuration)
					, trackedFactoryManager); 
			factory.configure(effective);
			adapter.setId(factory.getId());
			
			if (!factory.isValid())
				continue;

			Dictionary<String, String> props = new Hashtable<String, String>();
			props.put(EntaxyFactory.SERVICE.PROP_ID, factory.getId());
			props.put(EntaxyFactory.SERVICE.PROP_TYPE, factory.getType());
			props.put(EntaxyFactory.SERVICE.PROP_ORIGIN_BUNDLE, adapter.getBundleId()+"");				
			
			adapter.serviceRegistration = this.bundleContext.registerService(
					EntaxyFactory.class, 
					factory, 
					props);
			
			// register templates
			
			for (URL url: adapter.getTemplates())
				registerTemplate(url, adapter);
		}
	}

	@Override
	public void modified(List<TrackedAdapter> managedObject) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void removed(List<TrackedAdapter> managedObject) {
		for (TrackedAdapter adapter: managedObject)
			adapter.unregister();
	}

	protected void registerTemplate(URL templateUrl, TrackedAdapter adapter) {
		String templatePath = "/template";
		String localPath = templateUrl.toString();
		localPath = localPath.substring(localPath.indexOf(templatePath) + templatePath.length() + 1);
		String fullname = localPath.substring(localPath.lastIndexOf("/")+1);
		String path = localPath.lastIndexOf("/")>0 
				?localPath.substring(0, localPath.lastIndexOf("/"))
				:"";
		String fullPath = templatePath + "/" + path;
		String fileName = fullname.substring(0, fullname.lastIndexOf("."));
		String fileType = fullname.substring(fullname.lastIndexOf(".")+1);
		String id = CommonUtils.isValid(path) 
				?path.replace("/", ".") + "." + fileName
				:fileName;
		log.debug(":: localPath = " + localPath + "; fullName = " + fullname + "; fileName = " + fileName
				+ "; fileType = " + fileType + "; path = " + path);
		
		/*
		 * TemplateMetadata meta = new TemplateMetadata(); meta.setId(id);
		 * meta.setFilename(fileName); meta.setFullname(fullname); meta.setName(id);
		 * meta.setType(fileType); meta.setPath(fullPath);
		 * meta.setDescription("Found in bundle [" + adapter.getBundleId() +
		 * "] on path [" + localPath + "]"); ProvidedTemplate providedTemplate = new
		 * ProvidedTemplate(meta);
		 */		
		
		TemplateImpl impl = new TemplateImpl();
		impl.setId(adapter.getId() + "." + id);
		impl.setPath(fullPath);
		impl.setTemplateFullName(fullname);
		impl.setTemplateLocation("bundle://" + adapter.getBundleId() + ".0:0" + templatePath + "/");
		impl.setTemplateName(fileName);
		impl.setType(fileType);

		Dictionary<String, String> props = new Hashtable<String, String>();
		props.put(TemplateService.PROP_ID, impl.getId());
		props.put(TemplateService.PROP_NAME, fileName);
		props.put(TemplateService.PROP_TYPE, fileType);
		props.put(TemplateService.PROP_DESCRIPTION, "Template for adapter wrapper on bundle " + adapter.getBundleId());
		
		
		adapter.getTemplateRegistrations().add(
			this.bundleContext.registerService(Template.class, impl, props)	
		);
		
	}
	
}
