package com.example.patrice.rerservation01;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

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

// https://www.c-sharpcorner.com/article/load-image-from-internet-in-android/ a voir

public class affiche_jeu_DB_mysql extends AppCompatActivity
{
    private static String urlString;

    JSONArray element = null;

    private static final String TAG = "ERROR";
    private static final int IO_BUFFER_SIZE = 4 * 1024;

    private String string_JSON = "";

    ArrayList<HashMap<String, String>> AppArrList = new ArrayList<HashMap<String, String>>();

    ListView lstView1;

    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

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

        Toast.makeText(getApplicationContext(), "salut Patoche", Toast.LENGTH_LONG).show();

        // Permission StrictMode : utilisée lorsque que l'on ne veut pas utiliser une asynctask
        // maintenant elle n'est pas utile

        // par contre si la ligne (***) est modifiée , il faut la décommantée
/*
        if (android.os.Build.VERSION.SDK_INT > 9)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
*/
        lstView1 = (ListView)findViewById(R.id.listView1);

        urlString = "http://analog-design.net/WORKAREA/WEBSITE/reservation/query03.php";

        try
        {
            string_JSON = new ProcessJSON().execute(urlString).get();
        }

        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        catch (ExecutionException e)
        {
            e.printStackTrace();
        }


        // on transforme la chaine JSON en obj JSON pour extraire les datas
        try
        {
            JSONObject jObj = null;
            jObj = new JSONObject(string_JSON);
            element = jObj.getJSONArray("result");

            HashMap<String, String> map;

            for (int i = 0; i < element.length(); i++)
            {
                JSONObject x = element.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("id", x.getString("id"));
                map.put("nom", x.getString("nom"));
                map.put("image", x.getString("image"));
                map.put("description", x.getString("description"));
                AppArrList.add(map);
            }

        }

        catch (JSONException e)
        {
            e.printStackTrace();
        }

        lstView1.setAdapter(new ImageAdapter(this,AppArrList));
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);


        final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);

        lstView1.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {

                View layout = inflater.inflate(R.layout.image_capture_dialog, (ViewGroup) findViewById(R.id.layout_root));
                ImageView image = (ImageView) layout.findViewById(R.id.fullimage);


                try
                {
                   // image.setImageBitmap(loadBitmap(MyArr.get(position).get("image")));

                    Bitmap pic =  new BitmapWorkerTask().execute( MyArr.get(position).get("image") ).get();
                    image.setImageBitmap(pic);

                }
                catch (Exception e)
                {
                    // Error
                    image.setImageResource(android.R.drawable.ic_menu_report_image);
                }

                imageDialog.setIcon(android.R.drawable.btn_star_big_on);

                String s = MyArr.get(position).get("image");
                // http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/kate.jpeg
                String nom_image = s.substring(62);

                //imageDialog.setTitle("View : " + MyArr.get(position).get("image"));
                imageDialog.setTitle("View : " + nom_image );

                imageDialog.setView(layout);

                imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }

                });

                imageDialog.create();
                imageDialog.show();

            }
        });


    }

    private class ProcessJSON extends AsyncTask<String, Void, String>
    {
        protected String doInBackground(String... strings)
        {
            String stream = null;
            String urlString = strings[0];

            HTTPDataHandler hh = new HTTPDataHandler();
            stream = hh.GetHTTPData(urlString);

            // Return the data from specified url
            return stream;
        }

        protected void onPostExecute(String stream)
        {
        }

    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        //private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list)
        {
            context = c;
            MyArr = list;
        }

        public int getCount()
        {
            return MyArr.size();
        }

        public Object getItem(int position)
        {
            return position;
        }

        public long getItemId(int position)
        {
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent)
        {

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (convertView == null)
            {
                convertView = inflater.inflate(R.layout.affiche_jeu_ligne, null);
            }

            // ColImage
            ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
            imageView.getLayoutParams().height = 200;
            imageView.getLayoutParams().width = 200;
            //imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); // coup une partie de l'image

            try
            {
                // ancienne méthode qui ne fonctionne pas en mode background
                //imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));

                Bitmap pic =  new BitmapWorkerTask().execute( MyArr.get(position).get("image") ).get();
                imageView.setImageBitmap(pic);
            }

            catch (Exception e)
            {
                // When Error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            // ColPosition
            TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
            txtPosition.setPadding(10, 0, 0, 0);
            txtPosition.setText("ID : " + MyArr.get(position).get("id"));

            // ColPicname
            TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
            txtPicName.setPadding(50, 0, 0, 0);
            txtPicName.setText("Desc : " + MyArr.get(position).get("description"));

            return convertView;

        }

    }

    public static Bitmap loadBitmap(String url)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        int IO_BUFFER_SIZE = 4 * 1024;

        // NetworkOnMainThreadException  attention

        try
        {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        }

        catch (IOException e)
        {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        }

        finally
        {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

    private static void closeStream(Closeable stream)
    {
        if (stream != null)
        {
            try
            {
                stream.close();
            }

            catch (IOException e)
            {
                android.util.Log.e("TAG", "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException
    {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;

        while ((read = in.read(b)) != -1)
        {
            out.write(b, 0, read);
        }
    }

    ///////
    //Load bitmap in AsyncTask

    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)
        {
            //ImageView imageView = (ImageView) findViewById(R.id.ColImgPath);
            //imageView.setImageBitmap(bitmap);
            Bitmap img = bitmap;
            String tmp = "000";
            /*
            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;
    }
}

/**************************************************/
// pour récupérer la chaine json issue de la requête php
class HTTPDataHandler
{
    static String stream = null;

    public HTTPDataHandler()
    {
    }

    public String GetHTTPData(String urlString)
    {
        try
        {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Check the connection status
            if(urlConnection.getResponseCode() == 200)
            {
                // if response code = 200 ok
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                // Read the BufferedInputStream
                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null)
                {
                    sb.append(line);
                }
                stream = sb.toString();
                // End reading...............

                // Disconnect the HttpURLConnection
                urlConnection.disconnect();
            }
            else
            {
                // Do something
            }
        }

        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }

        catch(IOException e)
        {
            e.printStackTrace();
        }

        finally
        {

        }

        // Return the data from specified url
        return stream;
    }
}
