package com.nerdiex.dictionary.asynctask;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import com.nerdiex.dictionary.lib.DialogBuilder;
import com.nerdiex.dictionary.utils.Constant;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class DBDownloadTask extends AsyncTask<String, String, String> {
	private DialogBuilder mDialogBuilder;
	private Context context;
	private ProgressDialog pDialog;
	
	public DBDownloadTask(Context context){
		this.context = context;
	}
	@Override
	protected void onPreExecute() {
        super.onPreExecute();
        mDialogBuilder = new DialogBuilder(context);
        // Shows Progress Bar Dialog and then call doInBackground method
        pDialog = (ProgressDialog) mDialogBuilder.createDialog(DialogBuilder.DIALOG_PROGRESS);
		pDialog.show();
    }
	@Override
	protected String doInBackground(String... params) {
		int count;
        try {
            URL url = new URL(params[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // Get music file length
            int lenghtOfFile = conection.getContentLength();
            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(),10*1024);
            // Output stream to write file in SD card
            OutputStream output = new FileOutputStream(Constant.appPath + params[1] );
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // Publish the progress which triggers onProgressUpdate method
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // Write data to file
                output.write(data, 0, count);
            }
            // Flush output
            output.flush();
            // Close streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
	}
	@Override
	protected void onProgressUpdate(String... progress) {
        // Set progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }
	@Override
    protected void onPostExecute(String file_url) {
        // Dismiss the dialog after the language db downloaded
        pDialog.dismiss();
        Toast.makeText(context, "Download complete", Toast.LENGTH_LONG).show();
    }
}
