package itn.let.mjo.mjocommon;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;



public class MjonForienIpChk {

	@SuppressWarnings("unchecked")
	public static boolean getForienCountryValue(String ipNum) throws IOException{
		
		boolean resultSts = true;
		
		try {
			
			HttpClient httpClient = HttpClientBuilder.create().build(); 
			HttpGet httpGet = new HttpGet("https://api.iplocation.net/?cmd=ip-country&ip=" + ipNum); 
			httpGet.addHeader("Content-type", "application/json"); 
			httpGet.addHeader("Accept", "application/json");
			HttpResponse response = httpClient.execute(httpGet);
			
			String statusCode = Integer.toString(response.getStatusLine().getStatusCode());
			
			System.out.println(statusCode);
			
			//결과가 성공 이면
			if(statusCode.equals("200")) {
				
				String result = "";
				
				result = EntityUtils.toString(response.getEntity()); 
				//System.out.println("result : "+result);
				
				JSONParser parser = new JSONParser();
				Object obj = parser.parse(result);
				JSONObject object = (JSONObject) obj;
				String countryCode2 = object.get("country_code2").toString(); //String type으로 리턴 됨.
				String ipVersion = object.get("ip_version").toString(); //String type으로 리턴 됨.
				String country_name = object.get("country_name").toString(); //String type으로 리턴 됨.
				String ip = object.get("ip").toString(); //String type으로 리턴 됨.
				
				System.out.println("++++++++++++ countryCode2 ::: "+countryCode2);
				System.out.println("++++++++++++ ipVersion ::: "+ipVersion);
				System.out.println("++++++++++++ country_name ::: "+country_name);
				System.out.println("++++++++++++ ip ::: "+ip);
				
				if(!countryCode2.toLowerCase().equals("kr")) {
					
					resultSts = false;
					
				}
				
			}
			
			
		} catch (Exception e) {
			System.out.println("+++++++++++++++++++++++++++++++ MjonCommon Class getForienCountryValue Function Error !!! " + e);
		}
		
		return resultSts;
		
	}
}
