package com.example.svc.remote;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;

import com.example.svc.utilities.Downloader;

public class DownloadService4 extends Service {
    private static final int MSG_DOWNLOAD_START = 0;
    private static final int MSG_DOWNLOAD_STOP = 1;

    private class DownloadHandler extends Handler {
        private ThreadGroup threadGroup = new ThreadGroup("Download");

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_DOWNLOAD_START:
                download(msg.getData().getString("URL"));
                break;
            case MSG_DOWNLOAD_STOP:
                stopDownload();
                break;
            default:
                super.handleMessage(msg);
            }
        }

        private void download(final String url) {
            new Thread(threadGroup, new Runnable() {
                public void run() {
                    Downloader d = new Downloader(
                            getApplicationContext(), url);
                    d.interruptableDownloadFile();
                }
            }).start();
        }

        private void stopDownload() {
            threadGroup.interrupt();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Messenger messenger = new Messenger(new DownloadHandler());
        return messenger.getBinder();
    }
}