package fsenablers.android.http;

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

import fsenablers.android.BuildConfig;

import android.os.AsyncTask;
import android.util.Log;

public class HttpDownloadTask extends AsyncTask<String,String,String> {

	
	private IHttpResponseListener listener;
	
	public void setListener( IHttpResponseListener listener ) {
		this.listener = listener;
	}
	
	
	private static final String TAG = "Download";
	@Override
	protected String doInBackground(String... urls) {
        
        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
    	listener.onHttpResponse( result );
        // textView.setText(result);
   }
	
 // Given a URL, establishes an HttpUrlConnection and retrieves
 // the web page content as a InputStream, which it returns as
 // a string.
 private String downloadUrl(String myurl) throws IOException {
     InputStream is = null;
     // Only display the first 500 characters of the retrieved
     // web page content.
     int len = 500;
         
     try {
         URL url = new URL(myurl);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setReadTimeout(10000 /* milliseconds */);
         conn.setConnectTimeout(15000 /* milliseconds */);
         conn.setRequestMethod("GET");
         conn.setDoInput(true);
         // Starts the query
         conn.connect();
         int response = conn.getResponseCode();
         if( BuildConfig.DEBUG ) { Log.d(TAG, "The response is: " + response);}
         is = conn.getInputStream();

         // Convert the InputStream into a string
         BufferedReader br = new BufferedReader( new InputStreamReader( is ));
         StringBuffer buffer = new StringBuffer();
         String lineOfText = br.readLine();
         while( lineOfText != null ) {
        	 buffer.append( lineOfText );
        	 buffer.append( "\r\n" );
        	 lineOfText = br.readLine();
         }
         String contentAsString = buffer.toString();
         return contentAsString;
         
     // Makes sure that the InputStream is closed after the app is
     // finished using it.
     } finally {
         if (is != null) {
             is.close();
         } 
     }
 }	
}
