package be.iminds.ilabt.jfed.connectivity_tester;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * This class uses Java's URLConnection, which uses the proxy-properties 'http.proxyHost' and 'http.proxyPort'.
 * <p>
 * This test can be used to verify that the proxy-settings are correct.
 * <p>
 * User: twalcari
 * Date: 12/23/13
 * Time: 10:20 AM
 */
public class URLConnectionTest implements ConnectivityTest {
    private static final Logger LOG = LoggerFactory.getLogger(URLConnectionTest.class);

    private static final int TIMEOUT = 5000; //5 seconds

    @Nonnull
    private final URL url;

    private final String description;
    private final String category;

    public URLConnectionTest(@Nonnull URL url, String description, String category) {
        this.url = url;
        this.description = description;
        this.category = category;
    }

    @Override
    public String getName() {
        return String.format("[%s] %s", category, description);
    }

    @Override
    public boolean isLoginRequired() {
        return false;
    }

    @Override
    public ConnectivityTestResult call() {
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");

            //try to read from the connection
            if (conn.getResponseMessage() != null)
                return new ConnectivityTestResult(Status.SUCCEEDED, "Successfully connected to " + url.toExternalForm());
            else
                return new ConnectivityTestResult(Status.FAILED, "Could not connect to " + url.toExternalForm());
        } catch (IOException e) {
            return new ConnectivityTestResult(Status.FAILED, "Error while connecting to " + url.toExternalForm());
        }
    }
}
