/*-
 * ~~~~~~licensing~~~~~~
 * connection-producing
 * ==========
 * 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.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 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.impl.DefaultFactory;
import ru.entaxy.platform.base.support.CommonUtils;
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;
	
	public TrackedAdapterCustomizerListener(BundleContext bundleContext) {
		super();
		this.bundleContext = bundleContext;
	}
	
	@Override
	public void added(List<TrackedAdapter> managedObject) {
		
		for (TrackedAdapter adapter: managedObject) {

			// create factory
			
			AdapterWrapperDefaultFactory factory = new AdapterWrapperDefaultFactory();
			// factory.setFactoryId(adapter.getId());
			factory.configure(adapter.configuration);
			adapter.setId(factory.getFactoryId());
			
			if (!factory.isValid())
				continue;

			Dictionary<String, String> props = new Hashtable<String, String>();
			props.put(EntaxyFactory.SERVICE.PROP_ID, factory.getFactoryId());
			props.put(EntaxyFactory.SERVICE.PROP_TYPE, factory.getFactoryType());
			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)	
		);
		
	}
	
}
