package integration.proxy;

import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.proxy.SelenideProxyServer;
import integration.IntegrationTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

import static com.codeborne.selenide.Configuration.FileDownloadMode.PROXY;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.WebDriverRunner.*;
import static org.junit.jupiter.api.Assumptions.assumeFalse;

class ProxyServerUsageTest extends IntegrationTest {
  private List<String> requests = new ArrayList<>();
  private List<String> responses = new ArrayList<>();

  @BeforeEach
  @AfterEach
  void setUp() {
    assumeFalse(isPhantomjs()); // I don't know why, but PhantomJS seems to ignore proxy
    closeWebDriver();
    Configuration.fileDownload = PROXY;
  }

  @Test
  void canAddInterceptorsToProxyServer() {
    openFile("file_upload_form.html");

    SelenideProxyServer selenideProxy = getSelenideProxy();

    selenideProxy.addRequestFilter("proxy-usages.request", (request, contents, messageInfo) -> {
      String url = messageInfo.getUrl();
      if (!isBrowserOwnTechnicalRequest(url)) {
        requests.add(url + "\n\n" + contents.getTextContents());
      }
      return null;
    });
    selenideProxy.addResponseFilter("proxy-usages.response", (response, contents, messageInfo) -> {
      String url = messageInfo.getUrl();
      if (!isBrowserOwnTechnicalRequest(url)) {
        responses.add(url + "\n\n" + contents.getTextContents());
      }
    });

    $("#cv").uploadFromClasspath("hello_world.txt");
    $("#submit").click();

    assertThat(getSelenideProxy().getProxy())
      .as("Check browser mob proxy instance")
      .isNotNull();

    assertThat(requests)
      .withFailMessage("All requests: " + requests)
      .hasSize(1);
    assertThat(responses)
      .withFailMessage("All responses: " + responses)
      .hasSize(1);

    assertThat(requests.get(0)).contains("/upload");
    assertThat(requests.get(0)).contains("Content-Disposition: form-data; name=\"cv\"; filename=\"hello_world.txt\"");
    assertThat(requests.get(0)).contains("Hello, WinRar!");
    assertThat(responses.get(0)).contains("<h3>Uploaded 1 files</h3>");
  }

  private boolean isBrowserOwnTechnicalRequest(String url) {
    return url.contains("/favicon.ico") || url.contains("gstatic.com") || url.contains("google.com") || url.contains("mozilla.com");
  }
}

@@ -2496,24 +2496,30 @@
 google.com%22)
+%0A     
  %7C%7C url.cont
@@ -2537,16 +2537,46 @@
 la.com%22)
+%7C%7C url.contains(%22mozilla.net%22)
 ;%0A  %7D%0A%7D%0A

fix one more FF test on Jenkins