package com.example.svc.utilities;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class Downloader {
    private static String TAG = "Downloader";
    private Context ctx;
    private String url;

    public Downloader(Context ctx, String url) {
        this.ctx = ctx;
        this.url = url;
    }

    public void downloadFile() {
        Log.v(TAG, "Thread: " + Thread.currentThread().getName());

        try {
            Log.v(TAG, "Download File: " + url);
            // read data into a byte array
            URLConnection conn = new URL(url).openConnection();
            InputStream is = conn.getInputStream();
            int fileSize = conn.getContentLength();
            byte[] fileArray = new byte[fileSize];
            is.read(fileArray);

            String filename = extractFilenameFromURL(url);
            writeDataToFile(fileArray, filename);
            broadcastDownloadComplete(filename);
            Log.v(TAG, "Download Complete: " + filename);
        }
        catch (IOException e) {
            System.err.println(e);
        }
    }

    public void interruptableDownloadFile() {
        Log.v(TAG, "Thread: " + Thread.currentThread().getName());
        try {
            Log.v(TAG, "Download File: " + url);

            int bufferSize = 1024;

            URLConnection conn = new URL(url).openConnection();
            InputStream is = conn.getInputStream();
            int fileSize = conn.getContentLength();

            byte[] buffer = new byte[bufferSize];
            byte[] fileArray = new byte[fileSize];

            int bytesRead = 0;
            int position = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                System.arraycopy(buffer, 0, fileArray, position,
                        bytesRead);
                position += bytesRead;

                if (Thread.currentThread().isInterrupted()) {
                    System.err.println("Interrupted");
                    return;
                }
            }

            String filename = extractFilenameFromURL(url);
            writeDataToFile(fileArray, filename);
            broadcastDownloadComplete(filename);
            Log.v(TAG, "Download Complete: " + filename);

        }
        catch (IOException e) {
            System.err.println("Caught Exception: " + e);
        }
    }

    private String extractFilenameFromURL(String url) {
        String[] tokens = url.split("/");
        String filename = tokens[tokens.length - 1];
        return filename;
    }

    private void writeDataToFile(byte[] fileArray, String filename)
            throws IOException {
        FileOutputStream fos = ctx.openFileOutput(filename,
                Context.MODE_PRIVATE);
        fos.write(fileArray);
        fos.close();
    }

    private void broadcastDownloadComplete(String filename) {
        Intent intent = new Intent(
                "com.example.svc.DOWNLOAD_COMPLETE");
        intent.putExtra("Filename", filename);
        ctx.sendBroadcast(intent);
    }
}
