package org.arkiwi.app.service;

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

import org.arkiwi.app.utility.Download;

import android.app.Activity;
import android.app.IntentService;
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";
	private int resultDownload = Activity.RESULT_CANCELED;
	private File file;

	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 {	
			int cu = intent.getIntExtra("checkUpdate", 0);
		
			String urlfile = intent.getStringExtra("urlpath");
            URL url = new URL(urlfile);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String reldir = "";
            if (cu != CheckUpdate.NOTIFY_APP_UPDATE)
            	reldir = "downloads";
            
            file = Download.getFile(urlfile,reldir);
            if (file.exists() && cu != CheckUpdate.NOTIFY_APP_UPDATE){
            	resultDownload = Activity.RESULT_FIRST_USER;
        		Log.d(LOG_TAG,"stop");     			
        		sendNotification(intent);
            } else {
            	if (file.exists()) {
            		Log.d(LOG_TAG,"delete");
            		file.delete();
            	}

            	FileOutputStream fos = new FileOutputStream(file);
            	InputStream is = c.getInputStream();

            	byte[] buffer = new byte[1024];
            	int len1 = 0;
            	while ((len1 = is.read(buffer)) != -1) {
                	fos.write(buffer, 0, len1);
            	}
            	fos.close();
            	is.close();

    			if(cu == CheckUpdate.NOTIFY_APP_UPDATE) {
    				Intent installI = new Intent(Intent.ACTION_VIEW);
    				installI.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    				installI.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    				startActivity(installI);			
    			} else {
           	    	resultDownload = Activity.RESULT_OK;		
           	    	sendNotification(intent);
    			}
            }
        } catch (IOException e) {
            e.getStackTrace();
        }
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(LOG_TAG, "Service Destroyed");
	}
}