package athary.audio.ency;

import io.vov.utils.StringUtils;

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.URL;
import java.net.URLConnection;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.Toast;

public class DownloadService extends IntentService {
    public static final int UPDATE_PROGRESS = 8344;
    int fileLength = 0;
	private URL url;
	private URLConnection connection;
    public DownloadService() {
        super("DownloadService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        String urlToDownload = intent.getStringExtra("url");
        String Save_Path = intent.getStringExtra("save_place");

        ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {
        	//while (fileLength <=0){
        	url = new URL(urlToDownload);
            connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100% progress bar
            fileLength = connection.getContentLength();
        	//}
            // download the file
            String new_path= "/";
            for (int i = 0; i < Save_Path.split("/").length - 1; i++) {
            	new_path = new_path + Save_Path.split("/")[i].toString() + "/";
			}
           // Log.v("ATHARY", new_path);

                File file = new File(new_path);
                file.mkdirs();

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(Save_Path);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    Bundle resultData = new Bundle();
                    resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                    receiver.send(UPDATE_PROGRESS, resultData);
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
            //Toast.makeText(getApplicationContext(), "خطأ في تحميل الملف", Toast.LENGTH_SHORT).show();
        }

        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);
        receiver.send(UPDATE_PROGRESS, resultData);
    }
}
