/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * 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.factory.tracker;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.base.support.osgi.tracker.UniformBundleTrackerCustomizer;

public class TrackedFactoryCustomizer extends UniformBundleTrackerCustomizer<List<TrackedFactory>> {

	private static final Logger log = LoggerFactory.getLogger(TrackedFactoryCustomizer.class);
	
	private static final String FACTORY_ROOT_PATH = "/ru/entaxy/factory/";
	
	@Override
	protected List<TrackedFactory> createManagedObject(Bundle bundle, BundleEvent event,
			Map<String, List<?>> filterResults) {
		
		List<TrackedFactory> result = new ArrayList<>();
		
		Enumeration<URL> entries = bundle.findEntries(FACTORY_ROOT_PATH, "*.json", false);
		while (entries.hasMoreElements()) {
			URL entry = entries.nextElement();
			String urlString = entry.toString();
			log.debug("Found path: " + urlString);
			if (urlString.endsWith("/"))
				continue;
			String id = urlString.substring(urlString.lastIndexOf("/") + 1);
			id = id.substring(0, id.lastIndexOf("."));
			log.debug("Found id: " + id);
			
			try {
				String config = new BufferedReader (
						  new InputStreamReader(
								  entry.openStream(), StandardCharsets.UTF_8))
							.lines()
							.collect(Collectors.joining("\n"));
				TrackedFactory tf = new TrackedFactory();
				tf.setId(id);
				tf.setBundle(bundle);
				tf.setConfigString(config);
				result.add(tf);
			} catch (Exception e) {
				log.error("Error reading url: " + urlString, e);
			}
		}
		
		return result;
	}

	
	
}
