/*-
 * ~~~~~~licensing~~~~~~
 * profile-management
 * ==========
 * Copyright (C) 2020 - 2021 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.esb.platform.core.management.profile.impl;

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

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

import ru.entaxy.esb.platform.base.management.core.utils.ExtendedBundleTrackerCustomizer;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleCapabilityFilter;

public class DeployedProfileCustomizer extends ExtendedBundleTrackerCustomizer<List<ManagedProfile>> {

	@Override
	protected List<ManagedProfile> createManagedObject(Bundle bundle, BundleEvent event,
			Map<String, List<?>> filterResults) {
		@SuppressWarnings("unchecked")
		List<BundleCapability> capabilities = (List<BundleCapability>)filterResults.get(BundleCapabilityFilter.DEFAULT_FILTER_ID);
		if (capabilities==null)
			capabilities = new ArrayList<>();
		List<ManagedProfile> result = new ArrayList<>();
		for (BundleCapability capability: capabilities) {
			Object val = capability.getAttributes().get("name");
			String name = val==null?"":val.toString();
			if (!CommonUtils.isValid(name))
				continue;
			
			ManagedProfile mp = (new ManagedProfile())
					.name(name);
			enrich(bundle, event, filterResults, mp);
			result.add(mp);
		}
		return result;
	}

}
