package apiClients;



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

public class VoterApiClient {

	public  JsonObject callVoterApi(String epicNumber, String appUrl, String userId) throws Exception {
	    String urlStr = "https://gwitapi.in/SOFT/voteridHitJson.xhtml" +
	            "?epicNumber=" + epicNumber +
	            "&appUrl=" + appUrl +
	            "&userId=" + userId;
	    	
	    URL url = new URL(urlStr);
	    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	    conn.setRequestMethod("GET");
	    conn.setRequestProperty("Accept", "application/json");

	    try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
	        StringBuilder response = new StringBuilder();
	        String line;
	        while ((line = in.readLine()) != null) {
	            response.append(line);
	        }

	        String responseStr = response.toString().trim();
	        System.out.println("API Raw Response: " + responseStr);

	        responseStr = responseStr.replaceAll("<[^>]*>", "");

	        JsonReader reader = new JsonReader(new StringReader(responseStr));
	        reader.setLenient(true);
	        return JsonParser.parseReader(reader).getAsJsonObject();
	    }
	}


   

    public String getSafeString(JsonObject obj, String key) {
        if (obj.has(key) && !obj.get(key).isJsonNull()) {
            return obj.get(key).getAsString();
        }
        return null;
    }
}

