/*-
 * ~~~~~~licensing~~~~~~
 * system-commons
 * ==========
 * 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.system.common.osgi.impl;

import org.osgi.framework.ServiceReference;
import ru.entaxy.esb.system.common.osgi.NamedReferenceListener;

import java.util.*;

public abstract class CommonNamedReferenceListener<T> implements NamedReferenceListener<T> {

    protected Map<String, T> registeredReferences = new HashMap<String, T>();

    public void register(T service) throws Exception {
        if (service instanceof ServiceReference)
            return;
        String key = getObjectName(service);
        registeredReferences.put(key, service);
        doAfterRegister(service);
    }

    protected void doAfterRegister(T service) throws Exception {

    }

    protected void doBeforeUnregister(T service) throws Exception {

    }

    public void unregister(T service) throws Exception {
        if (service == null || service instanceof ServiceReference)
            return;
        doBeforeUnregister(service);
        registeredReferences.remove(getObjectName(service));
    }

    @Override
    public List<String> getReferenceNames() {
        List<String> result = new ArrayList<String>(registeredReferences.keySet());
        Collections.sort(result);
        return result;
    }

    @Override
    public T getReference(String referenceName) {
        return registeredReferences.get(referenceName);
    }

    public boolean isRegistered(String referenceName) {
        return registeredReferences.containsKey(referenceName);
    }

    protected abstract String getObjectName(T object);
}
