package com.example.svc.utilities;

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

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.example.svc.R;

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 interruptableDownloadFile() {
        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);
            notifyDownloadComplete(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 notifyDownloadComplete(String filename) {
        String downloadComplete = ctx
                .getString(R.string.downloadComplete);

        // Make the file readable by everyone
        File file = ctx.getFileStreamPath(filename);
        file.setReadable(true, false);

        Notification.Builder builder = new Notification.Builder(ctx)
                .setContentTitle(downloadComplete)
                .setContentText(filename)
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker(downloadComplete);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "image/*");
        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);
        builder.setAutoCancel(true);

        NotificationManager nm = (NotificationManager) ctx
                .getSystemService(Context.NOTIFICATION_SERVICE);

        nm.notify(1, builder.build());
    }
}
