package com.siginfo.controller;

import java.net.MalformedURLException;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.siginfo.vo.CrossRoadInfoHeaderVO;

import kr.co.smartguru.apim.gateway.util.APIMGatewayUtil;

public class HttpsClient {

	int     g_nResCode = -1;
	boolean g_bContent = false;
	
	private CrossRoadInfoHeaderVO headerVo;
	
	public HttpsClient() {
		this.headerVo = new CrossRoadInfoHeaderVO();
	}
	
	public CrossRoadInfoHeaderVO pingWeb(String svcId, String apimKey) throws Exception {
		
		//System.out.println("HTTPsClient.....");
		
		TWebPingConfig cfg = new TWebPingConfig();
		if (!cfg.loadConfig())
		{
			//System.out.println("HTTPsClient.....: loadConfig failed........");
			headerVo.setResultCode("01");
			headerVo.setResultMsg("APPLICATION_ERROR");
		}
		
		URL url;
		String sDbDriver = cfg.getDbDriver();
		String sDbUrl    = cfg.getDbUrl();
		String sDbUser   = cfg.getDbUser();
		String sDbPswd   = cfg.getDbPswd();
		String sPingUrl  = cfg.getPingUrl();
		
		try
		{
			url = new URL("http://"+sPingUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			g_nResCode = con.getResponseCode();
			print_content(con);
			
			if (g_nResCode == 200 || g_bContent == true) 
			{
				checkApimKey(apimKey);
			}
			else
			{
				headerVo.setResultCode("04");
				headerVo.setResultMsg("HTTP_ERROR1");
			}
		}
		catch (MalformedURLException e) 
		{
			headerVo.setResultCode("04");
			headerVo.setResultMsg("HTTP_ERROR2");
		}
		catch (IOException e) 
		{
			headerVo.setResultCode("04");
			headerVo.setResultMsg("HTTP_ERROR3");
		}
		
        String sSql1 = "INSERT INTO TB_OPENDB_SVC_HIST(SVC_ID, SVC_KEY, ERR_NO) "
				     + "VALUES('"+svcId+"','"+apimKey+"',"+ headerVo.getResultCode() + ")";

		Connection connect = null;
		Statement statement = null;
		ResultSet rs = null;

		try
		{
	        Class.forName(sDbDriver);
			connect = DriverManager.getConnection(sDbUrl, sDbUser, sDbPswd);
	        statement = connect.createStatement();
			statement.executeUpdate(sSql1);
			
			connect.commit();
		}
		catch (SQLException e) 
		{
			connect.close();
		}
		finally
		{
			if (statement != null) 
			{
				statement.close();
			}
			if (connect != null) 
			{
				connect.close();
			}
			if (rs != null) 
			{
				rs.close();
			}
		}

		return headerVo;
	}

	private void print_content(HttpURLConnection con) {
		
		if (con != null) 
		{
			try 
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
				String input;

				while ((input = br.readLine()) != null) 
				{
					if (input.equals("CHECKOK")) 
					{
						g_bContent = true;
						break;
					}
				}
				br.close();

			} catch (IOException e) 
			{
				//e.printStackTrace();
				return;
			}
		}
	}

	private void checkApimKey(String apimKey) {
		int checkResult = -1; // 인증결과 초기화
    	if (apimKey != null)
    	{
    		checkResult = APIMGatewayUtil.SG_APIM_Check(apimKey);
		 	// 인증키 확인(성공 시 1, 실패 시 -1 반환)
		 	if (checkResult == 1) { 
		 		headerVo.setResultCode("0");
		 		headerVo.setResultMsg("NORMAL_SERVICE");
		 	} else {
		 		headerVo.setResultCode("30");
		 		headerVo.setResultMsg("SERVICE_KEY_IS_NOT_REGISTERED_ERROR");
		 	} 
    	}
    	else 
    	{
    		headerVo.setResultCode("20");
    		headerVo.setResultMsg("SERVICE_ACCESS_DENIED_ERROR");
    	}
	}
}