package com.example.patrice.http01;

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 android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View.OnClickListener;

// https://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
public class DownloadFile extends Activity
{
    Button btnShowProgress;
    ProgressDialog pDialog;
    ImageView my_image;

    String file_url = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/photo.jpg";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_file_layout);

        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        my_image = (ImageView) findViewById(R.id.my_image);

        btnShowProgress.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                new DownloadFileFromURL().execute(file_url);
            }
        });
    }


    class DownloadFileFromURL extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(DownloadFile.this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... f_url)
        {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);
                // Output stream
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];
                long total = 0;

                while ((count = input.read(data)) != -1)
                {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();  // vers la sortie

                // closing streams
                output.close();
                input.close();

            }

            catch (Exception e)
            {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(String... progress)
        {
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String file_url)
        {
            pDialog.dismiss();
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }

    }
}