package com.github.dreamhead.moco.internal;

import com.github.dreamhead.moco.Request;
import com.github.dreamhead.moco.Response;
import com.github.dreamhead.moco.ResponseSetting;
import com.github.dreamhead.moco.setting.Setting;
import com.google.common.collect.ImmutableList;

import java.util.Optional;

public class Responser<T extends ResponseSetting<T>> {
    private final SettingFetcher<T> fetcher;

    public Responser(final SettingFetcher<T> fetcher) {
        this.fetcher = fetcher;
    }

    public final Optional<Response> getResponse(final SessionContext context) {
        Request request = context.getRequest();
        ImmutableList<Setting<T>> settings = fetcher.getSettings();
        for (Setting<?> setting : settings) {
            if (setting.match(request)) {
                setting.writeToResponse(context);
                return Optional.of(context.getResponse());
            }
        }

        Setting<T> anySetting = fetcher.getAnySetting();
        if (anySetting.match(request)) {
            anySetting.writeToResponse(context);
            return Optional.of(context.getResponse());
        }

        return Optional.empty();
    }
}

@@ -705,32 +705,48 @@
    f
-or (Setting%3C?%3E s
+inal Optional%3CSetting%3CT%3E%3E firstS
 etting 
-:
+=
  set
@@ -750,19 +750,25 @@
 settings
-) %7B
+.stream()
 %0A       
@@ -776,43 +776,125 @@
     
-if (setting.match(request)) %7B%0A     
+    .filter(setting -%3E setting.match(request))%0A                .findFirst();%0A        if (firstSetting.isPresent()) %7B%0A
     
@@ -900,24 +900,36 @@
         
-s
+ firstS
 etting.
+get().
 writeToR
@@ -938,36 +938,32 @@
 ponse(context);%0A
-    
             retu
@@ -1013,24 +1013,183 @@
     
+%7D%0A%0A        return getAnyResponse(context);%0A
     %7D%0A
+%0A
     
-    %7D%0A
+private Optional%3CResponse%3E getAnyResponse(final SessionContext context) %7B%0A        Request request = context.getRequest();
 %0A   

extracted any response in responser