package com.example.patrice.rerservation01;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class historique_retrait_jeu extends AppCompatActivity
{

    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();

    private static String url_requete_historique_emprunts = "http://analog-design.net/WORKAREA/WEBSITE/reservation/historique_emprunts.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_JEU = "jeu_emprunter";
    private static final String TAG_ID = "id";
    private static final String TAG_NOM = "jeu";
    private static final String TAG_STATUT = "statut";
    private static final String TAG_DATE_RETRAIT = "date_retrait";
    private static final String TAG_TIME_RETRAIT = "time_retrait";
    private static final String TAG_DATE_RETOUR = "date_retour";
    private static final String TAG_TIME_RETOUR = "time_retour";

    JSONParser jsonParser = new JSONParser();

    JSONArray datas = null;

    private ArrayList<Jeu_Listing> DB_Response;

    private ListView lv;

    private liste_restitution_adapter instance_listview_adapter;

    public static final String key_nom_utilisateur = "nom_utilisateur";

    String nom_uilisateur = "";

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

        nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);

        getSupportActionBar().setTitle("Historique de " + nom_uilisateur);
        getSupportActionBar().setLogo(R.drawable.user);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        new historique().execute();

    }

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

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

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

    class historique extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(historique_retrait_jeu.this);
            pDialog.setMessage("Chargement ...Patience.");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args)
        {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("client", "patoche"));
            //params.add(new BasicNameValuePair("client", nom_uilisateur));

            JSONObject json = jParser.makeHttpRequest(url_requete_historique_emprunts, "GET", params);
            Log.d("Affiche format JSON: ", json.toString());

            try
            {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1)
                {
                    datas = json.getJSONArray(TAG_JEU);

                    DB_Response = new ArrayList<>();

                    for (int i = 0; i < datas.length(); i++)
                    {
                        JSONObject c = datas.getJSONObject(i);
                        //String id = c.getString(TAG_ID);
                        String jeu = c.getString(TAG_NOM);
                        String statut = c.getString(TAG_STATUT);
                        String date_retrait = c.getString(TAG_DATE_RETRAIT);
                        String time_retrait = c.getString(TAG_TIME_RETRAIT);
                        String date_retour = c.getString(TAG_DATE_RETOUR);
                        String time_retour = c.getString(TAG_TIME_RETOUR);

                        DB_Response.add(new Jeu_Listing("", jeu ,statut, date_retrait, time_retrait, date_retour, time_retour ));
                    }
                }

                else
                {
                    // erreur
                }
            }

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

            return null;
        }

        protected void onPostExecute(String file_url)
        {

            pDialog.dismiss();

            lv = (ListView)findViewById(R.id.lv_emprunts);
            instance_listview_adapter = new liste_restitution_adapter(DB_Response, historique_retrait_jeu.this);
            lv.setAdapter(instance_listview_adapter);

        }
    }

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

    public class liste_restitution_adapter extends BaseAdapter
    {

        public class ViewHolder
        {
            TextView id, jeu, statut, date_heure_retrait, date_heure_retour;
        }

        public ArrayList<Jeu_Listing> elements_liste;

        public Context context;

        private liste_restitution_adapter(ArrayList<Jeu_Listing> apps, Context context)
        {
            this.elements_liste = apps;
            this.context = context;
        }

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

        @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 rowView = convertView;
            ViewHolder viewHolder;

            if (rowView == null)
            {
                LayoutInflater inflater = getLayoutInflater();

                rowView = inflater.inflate(R.layout.item_profile04, parent,false);

                viewHolder = new ViewHolder();

                viewHolder.id = (TextView) rowView.findViewById(R.id.id);
                viewHolder.jeu = (TextView) rowView.findViewById(R.id.jeu);
                viewHolder.statut = (TextView) rowView.findViewById(R.id.statut);
                viewHolder.date_heure_retrait = (TextView) rowView.findViewById(R.id.date_heure_retrait);
                viewHolder.date_heure_retour = (TextView) rowView.findViewById(R.id.date_heure_retour);

                rowView.setTag(viewHolder);
            }

            else
            {
                viewHolder = (ViewHolder) convertView.getTag();
            }


            int pos =  position + 1;

            // viewHolder.id.setText(elements_liste.get(position).getId() + "" );

            viewHolder.id.setText( String.valueOf(pos) );


            viewHolder.jeu.setText(elements_liste.get(position).getJeu() + "" );

            if(elements_liste.get(position).getStatut().equals("retour") )
            {
                viewHolder.statut.setText("Statut : Rendu");
            }

            if(elements_liste.get(position).getStatut().equals("retrait") )
            {
                viewHolder.statut.setText("Statut : Emprunt");
            }


            /******/

/*
            String infos_retrait = "";
            infos_retrait = "Retrait: " + elements_liste.get(position).getDateRetrait() + " à " + elements_liste.get(position).getTimeRetrait();
            viewHolder.date_heure_retrait.setText(infos_retrait);

            Button btn_delete = (Button) rowView.findViewById(R.id.btn_delete);

            String infos_retour = "";
            int len = elements_liste.get(position).getDateRetour().length();
            if(len == 0)
            {
                infos_retour = "";
            }
            else
            {
                infos_retour = "Retour: " + elements_liste.get(position).getDateRetour() + " à " + elements_liste.get(position).getTimeRetour();
            }

            viewHolder.date_heure_retour.setText(infos_retour);

            /******/

            Button btn_delete = (Button) rowView.findViewById(R.id.btn_delete);

            btn_delete.setVisibility(View.INVISIBLE);

            String statut = DB_Response.get(position).getStatut();

            String infos_retrait = "";
            infos_retrait = "Retrait: " + elements_liste.get(position).getDateRetrait() + " à " + elements_liste.get(position).getTimeRetrait();
            viewHolder.date_heure_retrait.setText(infos_retrait);

            String infos_retour = "";
            infos_retour = "Retour: " + elements_liste.get(position).getDateRetour() + " à " + elements_liste.get(position).getTimeRetour();
            viewHolder.date_heure_retour.setText(infos_retour);


            return rowView;

        }

    }

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


}