package com.example.download;

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

import android.app.Activity;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class DownloadFileActivity3 extends Activity implements
        FileChooserListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.downloadfile3);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new MyButtonListener());
    }

    class MyButtonListener implements OnClickListener {
        public void onClick(View v) {
            DialogFragment fragment = new ChooseFileDialogFragment();
            fragment.show(getFragmentManager(), "choose-file");
        }
    }

    @Override
    public void onFileChosen(String url) {
        new MyAsyncTask().execute(url);
    }

    class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        private ImageView imageView;
        private DialogFragment dialogFragment;

        @Override
        protected void onPreExecute() {
            imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(null);
            dialogFragment = new ProgressDialogFragment();
            dialogFragment.show(getFragmentManager(), "progress");
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            String url = params[0];

            try {
                int bufferSize = 1024;

                URLConnection conn = new URL(url).openConnection();
                InputStream is = conn.getInputStream();
                int imageSize = conn.getContentLength();

                byte[] buffer = new byte[bufferSize];
                byte[] imageArray = new byte[imageSize];
                int numberOfBuffers = imageSize / bufferSize;

                int bytesRead = 0;
                int position = 0;
                int progress = 0;
                while ((bytesRead = is.read(buffer)) != -1) {
                    System.arraycopy(buffer, 0, imageArray, position,
                            bytesRead);
                    position += bytesRead;

                    publishProgress(numberOfBuffers, ++progress);

                    try {
                        // slow things down so progress
                        // doesn't zip by too fast
                        Thread.sleep(100);
                    }
                    catch (InterruptedException e) {
                        System.err.println(e);
                    }
                }

                return BitmapFactory.decodeByteArray(imageArray, 0,
                        imageArray.length);
            }
            catch (IOException e) {
                System.err.println(e);
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            ProgressDialog pd = (ProgressDialog) dialogFragment
                    .getDialog();
            pd.setMax(values[0]);
            pd.setProgress(values[1]);
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            dialogFragment.dismiss();
            if (result != null) {
                imageView.setImageBitmap(result);
                DialogFragment fragment = new SuccessDialogFragment2();
                fragment.show(getFragmentManager(), "success");
            }
            else {
                DialogFragment fragment = new FailureDialogFragment2();
                fragment.show(getFragmentManager(), "failure");
            }
        }
    }
}