/*-
 * ~~~~~~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.service.tracker;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;

import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.service.impl.EntaxyObjectServiceImpl;
import ru.entaxy.platform.base.objects.service.impl.TrackedEntaxyObject;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.osgi.tracker.UniformBundleTrackerCustomizer;

public class TrackedEntaxyObjectCustomizer extends UniformBundleTrackerCustomizer<List<TrackedEntaxyObject>> {

	protected EntaxyObjectServiceImpl objectServiceImpl;
	
	public TrackedEntaxyObjectCustomizer(EntaxyObjectServiceImpl objectServiceImpl) {
		super();
		this.objectServiceImpl = objectServiceImpl;
	}
	
	@Override
	protected List<TrackedEntaxyObject> createManagedObject(Bundle bundle, BundleEvent event,
			Map<String, List<?>> filterResults) {
		
		List<TrackedEntaxyObject> result = new ArrayList<>();
		
		String objectsHeader = bundle.getHeaders().get(EntaxyObject.HEADERS.GENERATED_OBJECTS);
		String configHeader = bundle.getHeaders().get(EntaxyObject.HEADERS.GENERATED_OBJECTS_CONFIG);
		
		String[] objects = objectsHeader.split(",");
		String[] configs = configHeader.split(",");
		
		for (int i=0; i<objects.length; i++) {
			
			String[] objectData = objects[i].split(":");
			String configuration = configs[i];
			if (CommonUtils.isValid(configuration)) {
				byte[] bytes = Base64.getDecoder().decode(configuration);
				configuration = new String(bytes);
			} else {
				configuration = "{}";
			}
			
			TrackedEntaxyObject obj = TrackedEntaxyObject.create(
					objectServiceImpl.getBundleContext(), objectData[0], objectData[1]
			).bundle(bundle).configuration(configuration);
			result.add(obj);
		}
		
		return result;
	}
}
