package com.vaessl.app.search;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.vaessl.app.shared.ServiceItem;
import com.vaessl.app.shared.ServiceType;
import com.vaessl.app.exception.WrongServiceTypeException;

@Service
public class SearchService {

    private final Map<ServiceType, SearchProvider> providerRegistry;

    public SearchService(List<SearchProvider> providers) {
        Map<ServiceType, SearchProvider> registry = new EnumMap<>(ServiceType.class);
        for (SearchProvider provider : providers) {
            registry.put(provider.getServiceType(), provider);
        }
        this.providerRegistry = registry;
    }

    /**
     * Dispatches the paged search request to the provider registered for
     * {@link SearchRequest#serviceType()}.
     *
     * @param request the search request
     * @param pageable the Pageable interface
     * @return results returned by the matching provider
     * @throws WrongServiceTypeException if no provider is registered for the given service type
     */
    public Page<ServiceItem> search(SearchRequest request, Pageable pageable) {

        SearchProvider provider = providerRegistry.get(request.serviceType());

        if (provider == null) {
            throw new WrongServiceTypeException();
        }

        return provider.getSearchResults(request, pageable);
    }
}
