package com.eactive.eai.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.log4j.Logger;

public class HttpUtil {
	
	protected static final Logger logger = Logger.getLogger(HttpUtil.class);
	
	public static String httpCall(String urlStr, String httpMethod) throws Exception {
		return httpCall(urlStr, httpMethod, Charset.defaultCharset().toString());
	}

	public static String httpCall(String urlStr, String httpMethod, String encoding) throws Exception {
		
		logger.debug("httpCall (" +httpMethod+ ") : " + urlStr);

		StringBuilder result = new StringBuilder();

		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
			conn.setRequestMethod(httpMethod);
			BufferedReader rd = null;

			if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
				InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream(), encoding);
				rd = new BufferedReader(inputStreamReader);
			} else {
				logger.error(urlStr + " / ResponseCode : " + conn.getResponseCode());
				return null;
			}

			String line;

			while ((line = rd.readLine()) != null) {
				result.append(line);
			}

			rd.close();
			conn.disconnect();
		} catch (ConnectException e) {
			logger.error(urlStr + e.getMessage());
			return null;
		}

		return result.toString();
	}
	
	public static String httpCall(String urlStr, String httpMethod, String encoding, Map<String, String> paramMap) throws Exception {
		
		if(paramMap.size() < 0) {
			return httpCall(urlStr, httpMethod, encoding);
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append(urlStr);
		sb.append("?");
		
		paramMap.forEach((k, v) -> {
			sb.append(k);
			sb.append("=");
			sb.append(v);
			sb.append("&");
		});
		
		return httpCall(sb.toString(), httpMethod, encoding);
	}

}
