package com.example.patrice.rerservation01;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
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.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;

import com.example.patrice.rerservation01.imageutils.ImageLoader;

//https://github.com/ashishmishra007/Android-Asynchronous-Image-Loading-Example

public class listview_all_games_in_db_04 extends AppCompatActivity
{

    ListView list;
    Listview_image_Adapter adapter;

    JSONArray element = null;
    ArrayList<HashMap<String, String>> AppArrList = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String, String>> tempo = new ArrayList<HashMap<String, String>>();

    String[] imageUrls;

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

        /* action barre */
        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);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // trouver une façon pour avoir une allocation dynamique

        imageUrls = new String[400];

        list = (ListView) findViewById(R.id.listView1);

        // tâche de fond
        String urlString = "http://analog-design.net/WORKAREA/WEBSITE/reservation/query04.php";

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

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

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

        adapter = new Listview_image_Adapter(this, imageUrls, tempo);
        list.setAdapter(adapter);

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

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

            }
        });

    }

    @Override
    public void onDestroy()
    {
        list.setAdapter(null);
        super.onDestroy();
    }

    // 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>
    {

        @Override
        protected void onPreExecute()
        {
        }

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

            newHTTPDataHandler hh = new newHTTPDataHandler();
            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);
                    // chemin de l'image
                    imageUrls[i] = x.getString("image");
                }
            }

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

            return AppArrList; // a voir

        }

        @Override
        protected void onPostExecute(final ArrayList data)
        {
        }

    }

    class newHTTPDataHandler
    {
        String stream = null;

        public newHTTPDataHandler()
        {
        }

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

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



}

class Listview_image_Adapter extends BaseAdapter
{

    private Activity activity;
    private String[] data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader;

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

    public Listview_image_Adapter( Activity a, String[] d, ArrayList<HashMap<String, String>> list)
    {
        activity = a;
        data=d;
        MyArr = list;

        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount()
    {
        return data.length;
    }

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

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

    public View getView(int position, View convertView, ViewGroup parent)
    {
        View vi=convertView;

        if(convertView==null)
        {
            vi = inflater.inflate(R.layout.row_listview_item, null);

          //  vi = inflater.inflate(R.layout.list_item03, null);

        }

       // TextView text=(TextView)vi.findViewById(R.id.text);;
       //  ImageView image=(ImageView)vi.findViewById(R.id.image);

      //  text.setText( MyArr.get(position).get("nom") );

        TextView txtPosition = (TextView) vi.findViewById(R.id.id);
        txtPosition.setText("ID : " + MyArr.get(position).get("id"));

        TextView txtPicName = (TextView) vi.findViewById(R.id.nom);
        txtPicName.setText("Desc : " + MyArr.get(position).get("nom"));

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

        ImageView image = (ImageView) vi.findViewById(R.id.image);
        imageLoader.DisplayImage(data[position], image);

        return vi;
    }
}

