/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testmeetup;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * This class is designed to send QueryObjects and recieve the response.
 * @author Oriol
 */
public class QuerySender {
 
    /**
     * Sends query to Meetup using URL ,recieves response and checks for errors / API exceptions. Also checks for errors, reading the responseCode, and retries in case of error.
     * After a set number of tries with increasing time inbetween, desists an throws exception.
     * @param url URL of Meetup API.
     * @return Raw response as String.
     * @throws Exception 
     */
    public static String sendQuery(String url) throws Exception{
        StringBuffer response = new StringBuffer();
        int responseCode = 0;
        int tries = 0;
        int waitTimer = 5;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        Thread.sleep(1000); //Base sleep of 1 second
        con.setRequestMethod("GET"); //All meetup api methods needed are GET

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
       
        while(responseCode != 200 && tries < 3) {
            responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);
            if ( responseCode != 200 ){ //responseCode == 429 || responseCode == 403
                tries++;
                Thread.sleep(waitTimer*1000);
                waitTimer *= 2;
            }
            //Forbidden => Information is not public. Ex: Events are public but sometimes RSVP of events are not
            if (responseCode == 403 || responseCode == 500 || responseCode == 410 || responseCode == 404){ 
                throw new java.net.ProtocolException();
            }
            
        }

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


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

        //print result
        System.out.println(response.toString());
        return response.toString();
    }

}
