package com.eactive.eai.adapter.http.healthcheck;

import java.net.HttpURLConnection;
import java.net.URL;

import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.common.util.Logger;

public class HttpHealthChecker {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private String healthCheckUrl;
	private AdapterVO adapter;
	int timeoutMillis = 2000;
	
	
	public int getTimeoutMillis() {
		return timeoutMillis;
	}

	public void setTimeoutMillis(int timeoutMillis) {
		this.timeoutMillis = timeoutMillis;
	}

	public String getHealthCheckUrl() {
		return healthCheckUrl;
	}

	public void setHealthCheckUrl(String healthCheckUrl) {
		this.healthCheckUrl = healthCheckUrl;
	}

	public AdapterVO getAdapter() {
		return adapter;
	}

	public void setAdapter(AdapterVO adapter) {
		this.adapter = adapter;
	}

	public boolean isAlive() {
		HttpURLConnection connection = null;
		String debugPrefix = "HttpHealthChecker] " + adapter.getName() + " healthCheckUrl " + healthCheckUrl; 
		try {
			if(logger.isInfo()) {
	        	logger.info(debugPrefix);
	        }
			URL url = new URL(healthCheckUrl);
	        connection = (HttpURLConnection) url.openConnection();
	        connection.setRequestMethod("GET");
	        connection.setConnectTimeout(timeoutMillis); // Set connection timeout
	        connection.setReadTimeout(timeoutMillis); // Set read timeout
	
	        int responseCode = connection.getResponseCode();
	        boolean result = false;
	        if (responseCode == HttpURLConnection.HTTP_OK) {
	            result = true;
	        } 
	        
	        if(logger.isInfo()) {
	        	logger.info(debugPrefix + " returned a response code: " + responseCode);
	        }
	        return result;
		}
		catch(Exception ex) {
			logger.error(debugPrefix + " error", ex);
			return false;
		}
		finally {
			if(connection != null) {
				connection.disconnect();
			}
		}
	}
	
}
