package link;

import exeptions.URLIsNotReachable;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.UnknownHostException;

public class OnlineCheck {

	static Boolean isReachable(LinkUrl url) {
		int responseCode = getResponseCode(url);
		return (responseCode < 400 || responseCode == 401 || responseCode == 403);
	}

	private static int getResponseCode(LinkUrl url) {
		try {
			HttpURLConnection http = (HttpURLConnection) url.getUrl().openConnection();
			http.setRequestMethod("HEAD");
			http.disconnect();

			return http.getResponseCode();
		}
		catch (UnknownHostException unknownHostException){
			throw new URLIsNotReachable("The host of the url " + url + " could not be resolved.");
		}
		catch (IOException e) {
			throw new URLIsNotReachable("Something went wrong when trying to check if the url " + url + " is reachable. Make sure your internet connection is working: " + e.getMessage());
		}
	}
}
