package in.cdac.medinfo.csnotk.csnolib.disb.db;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpConnection {
	
	/**
	 * Validate URL and return true/ false for valid/invalid URL
	 * @param url {@link String} pass URL in string form
	 * @return true/false if URL is valid/invalid
	 * @throws IllegalArgumentException throws for wrong parameter
	 */
	private static boolean validateURL(String url)throws IllegalArgumentException{
		boolean isValidURL=false;
		if(url==null)
			throw new IllegalArgumentException("URL cannot be null");
		else if(url.isEmpty())
			throw new IllegalArgumentException("URL cannot be empty");	
		else 
			isValidURL=true;
		return isValidURL;
	}
	
	/**
	 * It will be use for retrieving {@link HttpURLConnection}
	 * @param url {@link String}
	 * @return true/false if URL is valid/invalid 
	 * @throws IllegalArgumentException throws for wrong parameter
	 * @throws MalformedURLException if any URL is not formed correctly
	 * @throws IOException throws for any IO operation
	 */
	public static HttpURLConnection getHttpURLConnection(String url)throws IllegalArgumentException, MalformedURLException, IOException{
		HttpURLConnection conn=null;
		if(validateURL(url)){
			conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            try{
            if (conn.getResponseCode() != 200){
                throw new RuntimeException("Failed : HTTP Error code : "+ conn.getResponseCode());
            }
            }catch(java.net.ConnectException e){
            	throw new java.net.ConnectException("Connection refused");
            }            
           }	
		return conn;		
	}
	
	/**
	 * Used for releasing {@link HttpURLConnection} object/resource
	 * @param conn {@link HttpURLConnection}
	 */
	public static void disconnectHttpConnection(HttpURLConnection conn){
		if(conn!=null)
			conn.disconnect();
	}
	
}
