package net.indivia.hacklabbo.statusreader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class Downloader extends IntentService {
	private static final String LOG_TAG = "Downloader";
    public static final int UPDATE_PROGRESS = 8344;
	private int resultDownload = Activity.RESULT_CANCELED;
	private File file;
	public ProgressDialog mProgressDialog;
	
	public Downloader() {
		super(LOG_TAG);
	}
	
	public void sendNotification(Intent i) {
		Bundle extras = i.getExtras();
		if (extras != null) {
			Messenger messenger = (Messenger) extras.get("messenger");
			Message msg = Message.obtain();
			msg.arg1 = resultDownload;
			msg.obj = file.getAbsolutePath();
			try {
				messenger.send(msg);
			} catch (android.os.RemoteException e1) {
				Log.w(getClass().getName(), "Exception sending message", e1);
			}

		}
	}	
	
	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			Log.d(LOG_TAG, "onHandIntent");
			int cu = intent.getIntExtra("checkUpdate", 0);
			String urlfile = intent.getStringExtra("urlpath");
            URL url = new URL(urlfile);
            
            file = SUtility.getFile(urlfile,"");
            if (cu != CheckUpdate.NOTIFY_APP_UPDATE){
            	Log.d(LOG_TAG,"file exist & cu != 2 - STOP");     			
            	resultDownload = Activity.RESULT_FIRST_USER;
        		sendNotification(intent);
            } else {
            	if (file.exists()) {
            		file.delete();
            	}
            	
                URLConnection c = (HttpURLConnection) url.openConnection();            
                c.connect();
                
                InputStream input = new BufferedInputStream(c.getInputStream());
                OutputStream output = new FileOutputStream(file);
                byte data[] = new byte[1024];
                int count;
                while ((count = input.read(data)) != -1) {
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                input.close();
                            
        		Intent i = new Intent(Intent.ACTION_VIEW);
        		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        		i.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        		startActivity(i);			
            }
        } catch (IOException e) {
            e.getStackTrace();
        }
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(LOG_TAG, "Service Destroyed");
	}
}