package com.bankaudit.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;

import org.jboss.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import com.bankaudit.constants.BankAuditConstant;

import javax.net.ssl.HttpsURLConnection;
public class VerifyRecaptcha {
	
	@Autowired
    private static Environment environment;

	static final Logger logger = Logger.getLogger(VerifyRecaptcha.class);
	
	//public static final String RECAPTCHA_SERVICE_URL = "https://www.google.com/recaptcha/api/siteverify";
	//public static final String SECRET_KEY = "6Lcl9rcpAAAAAMorY_u9niyEUb5gEgtmfQPU0sUS";
	public static final String SECRET_KEY = "6LdTlPsqAAAAAGJWwy6-IsuLKqLlnmC5nndPxeM9";
	//private final static String USER_AGENT = "Mozilla/5.0";
	
	//public static final String SECRET_KEY = environment.getRequiredProperty("recaptcha.SECRET_KEY");
	
	public static boolean verify(String gRecaptchaResponse) throws IOException {
		if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
			return false;
		}		 
		try{
			
			logger.info(" SECRET_KEY:::::::::::::"+SECRET_KEY);
			URL obj = new URL(BankAuditConstant.RECAPTCHA_SERVICE_URL);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

			con.setRequestMethod("POST");
			con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

			//add client result as post parameter
			String postParams = "secret=" + SECRET_KEY +"&response=" + gRecaptchaResponse;

			// send post request to google recaptcha server
			con.setDoOutput(true);
			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
			wr.writeBytes(postParams);
			wr.flush();
			wr.close();

			int responseCode = con.getResponseCode();

			logger.info("Post parameters: " + postParams);
			logger.info("Response Code: " + responseCode);

			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			logger.info(response.toString());

			//Parse JSON-response
			JSONParser parser = new JSONParser();
			JSONObject json = (JSONObject) parser.parse(response.toString());


			Boolean success = (Boolean) json.get("success");
			Double score = (Double) json.get("score");

			logger.info("success : " + success);
			logger.info("score : " + score);

			//result should be sucessfull and spam score above 0.5
			//return (success && score >= 0.5);
			return (success && score >= 0.05); // 
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
