package com.example.patrice.rerservation01;

        import android.app.ProgressDialog;
        import android.content.Context;
        import android.content.DialogInterface;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.os.AsyncTask;
        import android.support.v7.app.ActionBar;
        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.MenuItem;
        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.ProgressBar;
        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;

public class listview_all_games_in_db_03 extends AppCompatActivity
{
    private static String urlString;
    TextView textView_infos;

    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>>();

    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();

    ListView lstView1;

    private ProgressDialog pDialog;

    double taille = 0;

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

        ActionBar actionBar = getSupportActionBar(); // or getActionBar();
        getSupportActionBar().setTitle("Database des jeux"); // set the top title

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

        //getActionBar().setHomeButtonEnabled(true);
        //getActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        textView_infos = (TextView) findViewById(R.id.textView_infos);


        // 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/query04.php";

        new ProcessJSON().execute(urlString);


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

        // création de la dialoge box pour visualiser la boite du jeu
        final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);


        // OnClick
        lstView1.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {
                View layout = inflater.inflate(R.layout.custom_fullimage_dialog, (ViewGroup) findViewById(R.id.layout_root));
                ImageView image = (ImageView) layout.findViewById(R.id.fullimage);


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

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

                    if(pic == null)
                    {
                        image.setImageResource(android.R.drawable.ic_menu_report_image);
                    }
                    else
                    {
                        image.setImageBitmap(pic);
                    }

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

                imageDialog.setIcon(android.R.drawable.btn_star_big_on);
                imageDialog.setTitle("Jeu : " + AppArrList.get(position).get("nom"));
                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();

            }
        });

        // 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");

            int nb = element.length();
            String infos = "Jeux disponibles :" + Integer.toString(nb);
            textView_infos.setText(infos);

            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("barcode", x.getString("barcode"));
                AppArrList.add(map);
            }

            // création de la dialoge box pour visualiser la boite du jeu
            final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
            final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

            // OnClick
            lstView1.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id)
                {
                    View layout = inflater.inflate(R.layout.custom_fullimage_dialog, (ViewGroup) findViewById(R.id.layout_root));
                    ImageView image = (ImageView) layout.findViewById(R.id.fullimage);


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

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

                        if(pic == null)
                        {
                            image.setImageResource(android.R.drawable.ic_menu_report_image);
                        }
                        else
                        {
                            image.setImageBitmap(pic);
                        }

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

                    imageDialog.setIcon(android.R.drawable.btn_star_big_on);
                    imageDialog.setTitle("Jeu : " + AppArrList.get(position).get("nom"));
                    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();

                }
            });

        }

        catch (JSONException e)
        {
            e.printStackTrace();
        }
*/
        // lstView1.setAdapter(new ImageAdapter(this,AppArrList));
        //  final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

    }

    // pour le retour - inclus dans l'action bar ( < )
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private class ProcessJSON extends AsyncTask<String, Void, ArrayList>
    {

        ProgressDialog progressDialog;

        /*
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = new ProgressDialog(listview_all_games_in_db_03.this);
            //  progressDialog = new ProgressDialog(ctx);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner

            progressDialog.setTitle("Please Wait..");
            progressDialog.setMessage("Loading…");
            progressDialog.setCancelable(false);
            progressDialog.show();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(10000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    progressDialog.dismiss();
                }
            }).start();


        }
*/

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(listview_all_games_in_db_03.this);
            pDialog.setMessage("Chargement des jeux ... Patience");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected ArrayList doInBackground(String... strings)
        {
            String stream = null;
            String urlString = strings[0];

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

            try
            {
                JSONObject jObj = null;
                jObj = new JSONObject(stream);
                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("barcode", x.getString("barcode"));
                    AppArrList.add(map);

                    // on charge les jeux
                    Bitmap pic  = LoadImage( x.getString("image") );
                    // on les stockent dans un array de bitmap
                    bitmapArray.add(pic);

                  //  taille = taille + pic.getByteCount();

                }

            }

            catch (JSONException e)
            {
                e.printStackTrace();
            }
         /*
            catch (InterruptedException e) {
                e.printStackTrace();
            }

            catch (ExecutionException e) {
                e.printStackTrace();
            }
*/
            // Return the data from specified url


            return AppArrList; // a voir

        }

        @Override
        protected void onPostExecute(final ArrayList data)
        {

            // super.onPostExecute();
            //progressDialog.dismiss();
            pDialog.dismiss();

            //spinner.setVisibility(View.GONE);

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


        }

    }

    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.listview_all_games_item_layout, null);
                convertView = inflater.inflate(R.layout.list_item03, null);
            }

            // ColImage
            ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
            imageView.getLayoutParams().height = 200;
            imageView.getLayoutParams().width = 200;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            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);

                imageView.setImageBitmap( bitmapArray.get(position));

            }

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

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

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

            TextView txtBarcode = (TextView) convertView.findViewById(R.id.barcode);
            txtBarcode.setText("Code : " + MyArr.get(position).get("barcode"));



            if( position == 350)
            {
                pDialog.dismiss();
            }

            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)
        {
        }

       // Log.d("Chargement", URL);

        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;
    }
}

