package com.example.patrice.listview_image_download;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

//http://android-er.blogspot.fr/2015/04/async-load-image-from-internet-to.html

// https://www.androidhive.info/2012/07/android-loading-image-from-url-http/

public class MainActivity extends AppCompatActivity
{

    final static String src[] = {

            //"http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_1.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/a.jpeg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/b.jpeg",

            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_1.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_2.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_3.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_4.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_5.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_6.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_7.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_8.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_9.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_10.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_11.jpg",
            "http://analog-design.net/WORKAREA/WEBSITE/reservation/luba_74800_12.jpg",


            "http://2.bp.blogspot.com/--1K042_Nqow/VTeCrXE5BWI/AAAAAAAANL8/XLQo5gp6Zyg/s1600/_01.png",
            "http://2.bp.blogspot.com/-CP_IoxhknOQ/VTeCrag0-eI/AAAAAAAANMk/ruCd93vcqog/s1600/_02.png",
            "http://4.bp.blogspot.com/-1SEeDGnn7D4/VTeCrciCRNI/AAAAAAAANMA/QgFw2Jf_lm0/s1600/_03.png",
            "http://2.bp.blogspot.com/-vHYm6GYJ2Tw/VTeCsNtXFTI/AAAAAAAANMI/ArqK_hgjPew/s1600/_04.png",
            "http://1.bp.blogspot.com/-VnWqZvcqNOs/VTeCse3md5I/AAAAAAAANMM/LTXVII_Wp9k/s1600/_05.png",
            "http://3.bp.blogspot.com/-4LESmLLwFjU/VTeCs45dC4I/AAAAAAAANMg/r09uJJWk6qA/s1600/_06.png",
            "http://4.bp.blogspot.com/-AMGvPNdG6j0/VTeCs2swa2I/AAAAAAAANMc/NIg_i_2Et-A/s1600/_07.png",
            "http://4.bp.blogspot.com/-B59pQ2j1EtM/VTeCtsyD_QI/AAAAAAAANMo/7RvxFyINnr8/s1600/_08.png",
            "http://2.bp.blogspot.com/-VIUzes38Bro/VTeCuBX3dvI/AAAAAAAANMs/kiJM9ldSVho/s1600/_09.png",
            "http://4.bp.blogspot.com/-v618GyhX5U4/VTeCubGY43I/AAAAAAAANMw/X0uDVglfi1Q/s1600/_10.png",
            "http://2.bp.blogspot.com/-nhmSxu382f0/VTeCueNlxUI/AAAAAAAANM0/aan0OhOAStc/s1600/_11.png",
            "http://4.bp.blogspot.com/-WhB2MPTlGJk/VTeCuiosK6I/AAAAAAAANM4/ZdThfC14dOA/s1600/_12.png" };

    ListView imageList;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageList = (ListView) findViewById(R.id.imagelist);
        ArrayList<String> srcList = new ArrayList<String>(Arrays.asList(src));
        imageList.setAdapter(new CustomListAdapter(this, srcList));
    }

    // ----------------------------------------------------

    public class CustomListAdapter extends BaseAdapter
    {
        private ArrayList<String> listData;
        private LayoutInflater layoutInflater;

        public CustomListAdapter(Context context, ArrayList<String> listData) {
            this.listData = listData;
            layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int position) {
            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.row, null);
                holder = new ViewHolder();
                holder.icon = (ImageView)convertView.findViewById(R.id.icon);
                holder.text = (TextView)convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(String.valueOf(position));

            if (holder.icon != null) {
                new BitmapWorkerTask(holder.icon).execute(listData.get(position));
            }
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView text;
        }
    }

    // ----------------------------------------------------
    // Load bitmap in AsyncTask
    // ref:
    // http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
    class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
        private final WeakReference<ImageView> imageViewReference;
        private String imageUrl;

        public BitmapWorkerTask(ImageView imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage
            // collected
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        // Decode image in background.
        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            return LoadImage(imageUrl);
        }

        // Once complete, see if ImageView is still around and set bitmap.
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (imageViewReference != null && bitmap != null) {
                final ImageView imageView = imageViewReference.get();
                if (imageView != null) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        }

        private Bitmap LoadImage(String URL) {
            Bitmap bitmap = null;
            InputStream in = null;
            try {
                in = OpenHttpConnection(URL);
                bitmap = BitmapFactory.decodeStream(in);
                in.close();
            } catch (IOException e1) {
            }
            return bitmap;
        }

        private InputStream OpenHttpConnection(String strURL)
                throws IOException {
            InputStream inputStream = null;
            URL url = new URL(strURL);
            URLConnection conn = url.openConnection();

            try {
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    inputStream = httpConn.getInputStream();
                }
            } catch (Exception ex) {
            }
            return inputStream;
        }
    }



/*
    public void resize_pic()
    {
        // we'll start with the original picture already open to a file
        File imgFileOrig = getPic(); //change "getPic()" for whatever you need to open the image file.
        Bitmap b = BitmapFactory.decodeFile(imgFileOrig.getAbsolutePath());
// original measurements
        int origWidth = b.getWidth();
        int origHeight = b.getHeight();

        final int destWidth = 600;//or the width you need

        if(origWidth > destWidth){
            // picture is wider than we want it, we calculate its target height
            int destHeight = origHeight/( origWidth / destWidth ) ;
            // we create an scaled bitmap so it reduces the image, not just trim it
            Bitmap b2 = Bitmap.createScaledBitmap(b, destWidth, destHeight, false);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            // compress to the format you want, JPEG, PNG...
            // 70 is the 0-100 quality percentage
            b2.compress(Bitmap.CompressFormat.JPEG,70 , outStream);
            // we save the file, at least until we have made use of it
            File f = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "test.jpg");
            f.createNewFile();
            //write the bytes in file
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(outStream.toByteArray());
            // remember close de FileOutput
            fo.close();
        }

    }
*/
}