package org.carlspring.strongbox.providers.header;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

/**
 * @author carlspring
 */
@Component
public class HeaderMappingRegistry
{

    public static final String USER_AGENT_UNKNOWN = "unknown/*";

    private static final String USER_AGENT_FORMAT = "%s/*";

    private Map<String, List<String>> layout2UserAgentKeywodMap = new LinkedHashMap<>();

    public HeaderMappingRegistry()
    {
    }

    public void register(String layoutProviderAlias,
                         String... userAgentKeywords)
    {
        layout2UserAgentKeywodMap.put(layoutProviderAlias,
                                      Arrays.stream(userAgentKeywords)
                                            .map(s -> s.toUpperCase())
                                            .collect(Collectors.toList()));
    }

    public Optional<String> lookupUserAgent(String originalUserAgentHeaverValue)
    {
        if (originalUserAgentHeaverValue == null) {
            return Optional.empty();
        }
        
        return layout2UserAgentKeywodMap.values()
                                        .stream()
                                        .flatMap(l -> l.stream())
                                        .filter(s -> originalUserAgentHeaverValue.toUpperCase().contains(s))
                                        .map(s -> String.format(USER_AGENT_FORMAT, s))
                                        .findFirst();
    }

    public String defaultLayoutUserAgent(String layout)
    {
        return Optional.ofNullable(layout2UserAgentKeywodMap.get(layout))
                       .flatMap(s -> s.stream().findFirst())
                       .orElse(USER_AGENT_UNKNOWN);
    }

}

@@ -852,79 +852,8 @@
 ds)%0A
-                                            .map(s -%3E s.toUpperCase())%0A
     
@@ -924,16 +924,16 @@
 st()));%0A
+
     %7D%0A%0A 
@@ -1398,16 +1398,30 @@
 ntains(s
+.toUpperCase()
 ))%0A     
@@ -1464,48 +1464,26 @@
 map(
-s -%3E String.format(USER_AGENT_FORMAT, s)
+this::formatHeader
 )%0A  
@@ -1734,24 +1734,72 @@
 indFirst())%0A
+                       .map(this::formatHeader)%0A
             
@@ -1845,10 +1845,117 @@
 %0A    %7D%0A%0A
+    private String formatHeader(String s)%0A    %7B%0A        return String.format(USER_AGENT_FORMAT, s);%0A    %7D%0A%0A
 %7D%0A

support for multiple User-Agents per layout provider