/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package io.github.bonigarcia.wdm.test.server;

import static java.lang.invoke.MethodHandles.lookup;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.openqa.selenium.net.PortProber.findFreePort;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.Header;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test using wdm server.
 *
 * @author Boni Garcia
 * @since 3.0.0
 */
class ServerResolverTest {

    static final Logger log = getLogger(lookup().lookupClass());

    static final String EXT = IS_OS_WINDOWS ? ".exe" : "";

    static int serverPort;

    @BeforeAll
    static void startServer() throws IOException {
        serverPort = findFreePort();
        log.debug("Test is starting WebDriverManager server at port {}",
                serverPort);

        WebDriverManager
                .main(new String[] { "server", String.valueOf(serverPort) });
    }

    @ParameterizedTest
    @MethodSource("data")
    void testServerResolver(String path, String driver) throws IOException {
        String serverUrl = String.format("http://localhost:%s/%s", serverPort,
                path);
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpUriRequestBase request = new HttpGet(serverUrl);

            // Assert response
            log.debug("Request: GET {}", serverUrl);
            try (CloseableHttpResponse response = client.execute(request)) {
                int responseCode = response.getCode();
                log.debug("Response: {}", responseCode);

                assertThat(responseCode).isEqualTo(200);

                // Assert attachment
                String attachment = String.format("attachment; filename=\"%s\"",
                        driver);
                List<Header> headerList = Arrays.asList(response.getHeaders());
                List<Header> collect = headerList.stream().filter(
                        x -> x.toString().contains("Content-Disposition"))
                        .collect(toList());

                log.debug("Assessing {} ... headers should contain {}", driver,
                        attachment);
                assertThat(collect.get(0)).toString().contains(attachment);
            }
        }
    }

    static Stream<Arguments> data() {
        return Stream.of(Arguments.of("chromedriver", "chromedriver" + EXT),
                Arguments.of("firefoxdriver", "geckodriver" + EXT),
                Arguments.of("operadriver", "operadriver" + EXT),
                Arguments.of("edgedriver", "msedgedriver" + EXT),
                Arguments.of("chromedriver?os=WIN", "chromedriver.exe"),
                Arguments.of(
                        "chromedriver?os=LINUX&chromeDriverVersion=2.41&forceCache=true",
                        "chromedriver"));
    }

    @ParameterizedTest
    @ValueSource(classes = { ChromeOptions.class, FirefoxOptions.class })
    void testServerSeleniumServer(Class<? extends Capabilities> capabilities)
            throws Exception {
        String serverUrl = String.format("http://localhost:%s/", serverPort);

        Capabilities caps = capabilities.getDeclaredConstructor().newInstance();
        WebDriver driver = new RemoteWebDriver(new URL(serverUrl), caps);

        String sutUrl = "https://github.com/bonigarcia/webdrivermanager";
        driver.get(sutUrl);
        String title = driver.getTitle();
        log.debug("The title of {} is {}", sutUrl, title);

        assertThat(title)
                .contains("Automated driver management for Selenium WebDriver");

        driver.close();
    }

}

@@ -1069,30 +1069,8 @@
 n;%0D%0A
-import java.net.URL;%0D%0A
 impo
@@ -1735,298 +1735,8 @@
 e;%0D%0A
-import org.junit.jupiter.params.provider.ValueSource;%0D%0Aimport org.openqa.selenium.Capabilities;%0D%0Aimport org.openqa.selenium.WebDriver;%0D%0Aimport org.openqa.selenium.chrome.ChromeOptions;%0D%0Aimport org.openqa.selenium.firefox.FirefoxOptions;%0D%0Aimport org.openqa.selenium.remote.RemoteWebDriver;%0D%0A
 impo
@@ -4361,811 +4361,7 @@
 %0D%0A%0D%0A
-    @ParameterizedTest%0D%0A    @ValueSource(classes = %7B ChromeOptions.class, FirefoxOptions.class %7D)%0D%0A    void testServerSeleniumServer(Class%3C? extends Capabilities%3E capabilities)%0D%0A            throws Exception %7B%0D%0A        String serverUrl = String.format(%22http://localhost:%25s/%22, serverPort);%0D%0A%0D%0A        Capabilities caps = capabilities.getDeclaredConstructor().newInstance();%0D%0A        WebDriver driver = new RemoteWebDriver(new URL(serverUrl), caps);%0D%0A%0D%0A        String sutUrl = %22https://github.com/bonigarcia/webdrivermanager%22;%0D%0A        driver.get(sutUrl);%0D%0A        String title = driver.getTitle();%0D%0A        log.debug(%22The title of %7B%7D is %7B%7D%22, sutUrl, title);%0D%0A%0D%0A        assertThat(title)%0D%0A                .contains(%22Automated driver management for Selenium WebDriver%22);%0D%0A%0D%0A        driver.close();%0D%0A    %7D%0D%0A%0D%0A
 %7D%0D%0A

Remove Selenium Server test from resolver class