package com.takensoft.pohangTp.common.util;



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import com.takensoft.pohangTp.common.connection.api.vo.ApiParam;


/**
 * @author 김성원
 * @since 2024.01.12
 * 
 * 데이터 수집 - HTTP통신 관련 Util 입니다. 
 */
public class HTTPUtil {
	
	
	/**
	 * @author 김성원
	 * @since 2024.01.12
	 * 
	 * [GET] HTTP 통신
	 */
	public synchronized String HttpConnectionApi (String urlText, int type,  List<ApiParam>  parameter) {
		StringBuffer response = new StringBuffer();
		
		URL url = null;
		try {
			if (parameter.isEmpty() == false) {
				urlText += "?" + createUrlQueryApi(parameter, "UTF-8"); 
			}	
			url = new URL(urlText);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		HttpURLConnection httpCon = null;
		try {
			
			/* Connection */
			httpCon = (HttpURLConnection) url.openConnection();
			if(type == 1) {
				httpCon.setRequestMethod("POST");
			}else {
				httpCon.setRequestMethod("GET");
			}
			
			httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");
			httpCon.setConnectTimeout(1000 * 60);//http통신 최대 커넥션 시간(1분)
			httpCon.setReadTimeout(1000 * 60);//http통신 커넥션 이후, 데이터를 받아오는데 걸리는 최대 시간(1분)
			httpCon.setDoInput(true);//받아올 데이터가 있을 때, 사용
			
			//HTTP Request 결과 코드
			int responseCode = httpCon.getResponseCode();
			if (responseCode == 200) {
				//Response 결과 데이터 받기
				BufferedReader input = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
				
				//Response 결과 데이터를 문자열로 만들기
				String result = null;
				while ((result = input.readLine()) != null) {
					response.append(result);
				}
				
				//InputStream, BufferedReader 종료
				input.close();
				
				//HTTP Connection 종료
				httpCon.disconnect();
				
			} else {
				System.out.println("[HTTP]" + url + "(" + responseCode + " 에러)");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//문자열로된 Response 결과 return
		return response.toString();
	}
	
	/**
	 * @author 김성원
	 * @since 2024.01.12
	 * 
	 * 파라메터 데이터를 HTTP통신을 위한 문자열로 변환시켜주는 메서드
	 * Map -> String
	 */
	public String createUrlQueryApi (List<ApiParam> parameter, String incoding) {
		if (parameter.isEmpty() == true) {
			return "";
		} else {
			
		
			StringBuilder query = new StringBuilder();
		    for(ApiParam param : parameter) {		   
		        try {
		        	
		        	// 날짜 변경 처리 
		        	if(param.isDateForm() == true) {		        		
		        			param.setValue(StringUtil.getTodayaddDate(param.getValue().toString(),param.getDateType(), param.getAddDate()));
		        		        		
		        	}		        
		        	
		        	if(query.length() > 0) {
		        		query.append('&');
		        	}
		        	
		        	if (StringUtil.isEmpty(incoding) == true) {
		        		query.append(param.getKey());
			        	query.append('=');
			        	query.append(param.getValue());
		        	} else {
		        		query.append(URLEncoder.encode(param.getKey(), incoding));
			        	query.append('=');
			        	if(param.isDisableDecode()) {
			        		query.append(param.getValue());
			        	}else {
			        		query.append(URLEncoder.encode(String.valueOf(param.getValue()), incoding));
			        	}			        
		        	}		        	
		        
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
		    }
		    
		    return query.toString();
		}
	}
	
}
