package com.example.patrice.reservation02;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
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.ShareActionProvider;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.widget.Toast;


import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

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.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;


// SELECT column1, column2, ...
//FROM table_name
//        ORDER BY column1, column2, ... ASC|DESC;


public class all_games_in_db extends AppCompatActivity
{

    ListView listView;

    Menu mMenu;

    Menu menu;

    MenuItem toti;

    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;

    ArrayList<String> arrlist = new ArrayList<String>();

    ArrayList<String> infos = new ArrayList<String>();

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

    int nb_retraits = 0;

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

    ShareActionProvider provider;


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

        imageUrls = new String[500];

/*
        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        boolean key_existe = sp.contains("size");
        if(key_existe)
        {
            toti.setVisible(true);
            int size = sp.getInt("size", 0);
            f1();

            //menu.findItem(R.id.action_panier).setVisible(false);

            //mMenu.findItem(R.id.action_panier).setVisible(true);
          //  mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
        }
*/

        // tâche de fond
        String urlString = "http://analog-design.net/WORKAREA/WEBSITE/reservation/query05.php";
        try {
            tempo = new ProcessJSON().execute(urlString).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        int nb_jeu = tempo.size();

        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(all_games_in_db.this);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());

        //listView = (ListView) findViewById(android.R.id.listView1);

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

        ((ListView) listView).setAdapter(new ImageAdapter(all_games_in_db.this, imageUrls, arrlist , tempo));

        //adapter = new image_listview_adapter(this, imageUrls, tempo);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                //startImagePagerActivity(position);

                String nom = MyArr.get(position).get("nom");
                int index = position + 1;

                String statut = MyArr.get(position).get("statut");

                //  if(statut.equals("disponible"))

                if(statut.equals("retrait"))
                {
                    //Toast.makeText(getApplicationContext(), " Indisponible ! ", Toast.LENGTH_SHORT).show();
                    dialog_indisponible_retrait();
                }
                else {
                    Intent i = new Intent(getApplicationContext(), emprunter_by_listview.class);
                    i.putExtra("jeu", nom);
                    startActivity(i);

                    Toast.makeText(getApplicationContext(), nom + " " + index, Toast.LENGTH_SHORT).show();
                }
            }
        });


        getSupportActionBar().setTitle("   Jeux CEX " + nb_jeu + " (" + nb_retraits +")" );
        getSupportActionBar().setLogo(R.drawable.books);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(true);

    }

    private void dialog_indisponible_retrait()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Attention !");
        builder.setMessage("Ce jeux est dans disponible, s'adresser à l'emprunteur indiquer ci-dessous");

        builder.setCancelable(false);

        builder.setNegativeButton("Close", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "Abandon", Toast.LENGTH_SHORT).show();
            }
        });

        builder.show();
    }

    /*************************************************************************/

    // 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);
        }
    }
*/
    /*************************************************************************/

    public class ImageAdapter extends BaseAdapter {

        String[] IMAGE_URLS;
        //String[] IMAGE_URLS = null;

        private LayoutInflater inflater;
        //  private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();

        private DisplayImageOptions options;

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

            infos = items;

            //IMAGE_URLS =  d; //Constants.IMAGES; // d

            inflater = LayoutInflater.from(activity);

            options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.ic_stub)
                    .showImageForEmptyUri(R.drawable.ic_empty)
                    .showImageOnFail(R.drawable.ic_error)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .considerExifParams(true)
                    //.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))
                    .displayer(new SimpleBitmapDisplayer())

                    .build();

        }

        /*
                ImageAdapter(Context context) {
                    inflater = LayoutInflater.from(context);

                    options = new DisplayImageOptions.Builder()
                            .showImageOnLoading(R.drawable.ic_stub)
                            .showImageForEmptyUri(R.drawable.ic_empty)
                            .showImageOnFail(R.drawable.ic_error)
                            .cacheInMemory(true)
                            .cacheOnDisk(true)
                            .considerExifParams(true)
                            //.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))
                            .displayer(new SimpleBitmapDisplayer())

                            .build();
                }
        */
        @Override
        public int getCount()
        {
            return MyArr.size();
            //return IMAGE_URLS.length;
        }

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

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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View view = convertView;
            final ViewHolder holder;

            if (convertView == null)
            {
                //view = inflater.inflate(R.layout.item_list_image, parent, false);
                view = inflater.inflate(R.layout.row_listview_item02, parent, false);
                holder = new ViewHolder();

                holder.id = (TextView) view.findViewById(R.id.id);
                holder.nom = (TextView) view.findViewById(R.id.nom);
                holder.barcode = (TextView) view.findViewById(R.id.barcode);
                holder.description = (TextView) view.findViewById(R.id.description);
                holder.emprunteur = (TextView) view.findViewById(R.id.emprunteur);

                //holder.text = (TextView) view.findViewById(R.id.text);
                holder.image = (ImageView) view.findViewById(R.id.image);
                view.setTag(holder);
            }

            else
            {
                holder = (ViewHolder) view.getTag();
            }


            String statut = MyArr.get(position).get("statut");

            if(statut.equals("disponible"))
            {
                view.setBackgroundColor(Color.parseColor("#FF25FF51"));
                holder.emprunteur.setText(MyArr.get(position).get(""));
            }

            // le jeu a été retirer par un client = emprunteur
            else
            {
                view.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
                holder.emprunteur.setText(MyArr.get(position).get("emprunteur"));
            }


            // Change Every Value in a Column
            //UPDATE table SET colname = '999'
            // UPDATE table SET column = NULL;

            // UPDATE appli_table_jeu SET emprunteur = 'personne';

            // dans mysql 1 à 361

            // dans le tableau de retour JSON on va de 0 à 360

            //holder.text.setText("Item " + (position + 1));

            //String s = MyArr.get(position).get("nom");
            //holder.text.setText(s);


            //if(position < 361)
            //{
//            holder.id.setText(MyArr.get(position).get("id"));  changement le 12 Mai 2018
            int indice = position + 1;
            holder.id.setText(Integer.toString(indice));


            holder.nom.setText(MyArr.get(position).get("nom"));

            String val = MyArr.get(position).get("barcode");
            if(val.equals("null"))
            {
                val = "Not define";
            }

            holder.barcode.setText(val);
            holder.description.setText("Not define");

            String blase_jeu = MyArr.get(position).get("nom");
            String blase_barcode = MyArr.get(position).get("barcode");
            String blase_image = MyArr.get(position).get("image");


            ImageLoader.getInstance().displayImage(MyArr.get(position).get("image") , holder.image, options);
            // }

            //  ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options); //, animateFirstListener);



            return view;
        }
    }

    static class ViewHolder
    {
        TextView text;
        ImageView image;

        TextView id, nom, barcode, description, emprunteur;


    }


    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"));
                    map.put("statut", x.getString("statut"));
                    map.put("emprunteur", x.getString("emprunteur"));

                    if( x.getString("statut").equals("retrait") )
                    {
                        nb_retraits = nb_retraits + 1;
                    }

                    AppArrList.add(map);

                    imageUrls[i] = x.getString("image");

                    arrlist.add(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;
        }
    }


    /******************************************************************/

    //onPrepareOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        this.menu = menu;

        getMenuInflater().inflate(R.menu.test_menu, menu);

        mMenu = menu;
        mMenu.findItem(R.id.action_panier).setVisible(false);

        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        boolean key_existe = sp.contains("size");
        if(key_existe)
        {
            mMenu.findItem(R.id.action_panier).setVisible(true);
            mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
        }


        // Get the ActionProvider for later usage
        //provider = (ShareActionProvider) menu.findItem(R.id.action_panier)       .getActionProvider();

        //   toti = menu.findItem(R.id.action_panier);

        return true;
    }


    //gère le click sur une action de l'ActionBar
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()){
            case R.id.action_panier:
                f1();
                return true;
            //case R.id.action_aide:
            //    f2();
            //    return true;
            case R.id.action_a_propos:
                return true;
            case android.R.id.home:
                this.finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /*
        public boolean onPrepareOptionsMenu(Menu menu){
    //code here

            this.menu = menu;

            getMenuInflater().inflate(R.menu.test_menu, menu);

            mMenu = menu;
            mMenu.findItem(R.id.action_panier).setVisible(false);

            SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            boolean key_existe = sp.contains("size");
            if(key_existe)
            {
                mMenu.findItem(R.id.action_panier).setVisible(true);
                mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
            }
            else {
                mMenu.findItem(R.id.action_panier).setVisible(false);
            }

            return super.onPrepareOptionsMenu(menu);
        }
    */
    public void f1()
    {
        Intent i = new Intent(getApplicationContext(), emprunter_by_listview.class);
        startActivity(i);

        Toast.makeText(getApplicationContext(), " F1 ", Toast.LENGTH_SHORT).show();

    }

    public void f2()
    {
        Toast.makeText(getApplicationContext(), " F2 ", Toast.LENGTH_SHORT).show();

    }


 /*   @Override
    protected void onResume()
    {
        super.onResume();

        Toast.makeText(getApplicationContext(), " RESUME ", Toast.LENGTH_LONG).show();
        mMenu.findItem(R.id.action_panier).setVisible(true);
    }
*/

    @Override
    public void onRestart()
    {
        super.onRestart();

        //   Toast.makeText(getApplicationContext(), " RESTART ", Toast.LENGTH_LONG).show();

        SharedPreferences sp = getSharedPreferences("debug_PREFERENCE", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        boolean key_existe = sp.contains("size");
        if(key_existe)
        {
            mMenu.findItem(R.id.action_panier).setVisible(true);
            mMenu.findItem(R.id.action_panier).setIcon(getResources().getDrawable(R.drawable.shopping_cart));
        }
        else {
            mMenu.findItem(R.id.action_panier).setVisible(false);
        }


    }




}

