/*-
 * ~~~~~~licensing~~~~~~
 * search-service
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.search.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;

import ru.entaxy.platform.search.SearchProvider;
import ru.entaxy.platform.search.SearchService;

@Component(service = SearchService.class, immediate = true)
public class SearchServiceImpl implements SearchService {

    protected final Map<String, List<SearchProviderContainer>> providers = new HashMap<>();

    protected final Map<SearchProvider, SearchProviderContainer> containers = new HashMap<>();

    protected Object providersLock = new Object();

    protected BundleContext bundleContext;

    @Activate
    public void activate(ComponentContext componentContext) {
        this.bundleContext = componentContext.getBundleContext();
    }

    @Reference(unbind = "unbindProvider", cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC,
            policyOption = ReferencePolicyOption.GREEDY)
    public void bindProvider(SearchProvider provider, Map<String, Object> properties) {
        synchronized (providersLock) {
            SearchProviderContainer container = new SearchProviderContainer(provider, properties);
            for (String s : provider.getTargetTypes()) {
                if (!providers.containsKey(s))
                    providers.put(s, new ArrayList<>());
                providers.get(s).add(container);
            }
            containers.put(provider, container);
        }
    }

    public void unbindProvider(SearchProvider provider) {
        synchronized (providersLock) {
            SearchProviderContainer container = containers.get(provider);
            containers.remove(provider);
            if (container != null)
                for (String s : provider.getTargetTypes()) {
                    List<SearchProviderContainer> list = providers.get(s);
                    if (list != null)
                        list.remove(container);
                }
        }
    }

    @Override
    public List<SearchProvider> getProviders() {
        return this.providers.keySet().stream().map(t -> getProviderForType(t)).filter(p -> p != null).distinct()
                .collect(Collectors.toList());
    }

    @Override
    public SearchProvider getProviderForType(String targetType) {
        if (providers.containsKey(targetType)) {
            List<SearchProviderContainer> list = providers.get(targetType);
            if (list == null || list.isEmpty())
                return null;

            SearchProviderContainer targetContainer = list.stream().sorted(new Comparator<SearchProviderContainer>() {

                @Override
                public int compare(SearchProviderContainer o1, SearchProviderContainer o2) {
                    return Integer.compare(o1.ranking, o2.ranking);
                }
            }).findFirst().get();

            return targetContainer.provider;

        }
        return null;
    }

    protected class SearchProviderContainer {

        int ranking = 0;
        SearchProvider provider;

        protected SearchProviderContainer(SearchProvider provider, Map<String, Object> properties) {
            this.provider = provider;
            if (properties.containsKey(Constants.SERVICE_RANKING)) {
                Object rankingValue = properties.get(Constants.SERVICE_RANKING);
                if (rankingValue != null)
                    try {
                        if (rankingValue instanceof Number)
                            ranking = ((Number) rankingValue).intValue();
                    } catch (Exception e1) {
                        try {
                            ranking = Integer.parseInt(rankingValue.toString());
                        } catch (Exception ignore) {
                            // NOOP
                        }
                    }
            }
        }

    }

}
