package com.javacodegeeks.android.androidintentexample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class LoadWebPageService extends Service {

	private int MSG_ID = 2;

	public LoadWebPageService() {
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onCreate() {

	}

	@Override
	public void onStart(Intent intent, int startId) {

		String response = "";

		Bundle extras = intent.getExtras();
		

		if (extras != null) {
			Messenger messenger = (Messenger) extras.get("MESSENGER");
			String url = extras.getString("URL");
			CommunicationThread comm = new CommunicationThread(messenger, url);
			new Thread(comm).start();
		}

	}

	@Override
	public void onDestroy() {

	}

	class CommunicationThread implements Runnable {

		private Messenger messenger;
		String url;

		public CommunicationThread(Messenger messenger, String url) {

			this.messenger = messenger;
			this.url = url;
		}

		public void run() {
			
			String response = "";

			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);

			try {
				HttpResponse execute = client.execute(httpGet);
				InputStream content = execute.getEntity().getContent();

				BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
				String s = "";

				while ((s = buffer.readLine()) != null) {
					response += s;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			Message msg = Message.obtain();
			msg.arg1 = MSG_ID;
			msg.obj = response + "Hello";
			try {
				messenger.send(msg);
			} catch (android.os.RemoteException re) {
				Log.w(getClass().getName(), "Exception sending message", re);
			}

		}

	}
}
