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 restituer_jeu extends AppCompatActivity
{

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

    private static String url_requete_emprunts = "http://analog-design.net/WORKAREA/WEBSITE/reservation/requete_emprunts.php";
    private static String url_restituer_emprunts = "http://analog-design.net/WORKAREA/WEBSITE/reservation/restituer_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("Emprunts de " + nom_uilisateur);
        getSupportActionBar().setLogo(R.drawable.user);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        new restituter_jeu().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 restituter_jeu extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(restituer_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_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, "", "" ));

                    }
                }

                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, restituer_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 MyAppAdapter(ArrayList<ProfileModel02> apps, 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();
            }

            //viewHolder.username.setText(profileList.get(position).getUsername()+"");
            //viewHolder.country.setText(profileList.get(position).getCountry()+"");

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


            /******/

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

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

            /******/

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

            if(statut.equals("retour") )
            {
                btn_delete.setVisibility(View.GONE);
            }
            else // toujours en retrait
            {
                btn_delete.setVisibility(View.VISIBLE);

                btn_delete.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        String titre_jeu = DB_Response.get(position).getJeu();
                        String msg = "Restitution du jeu " + "\n" + titre_jeu;
                        AlertDialog.Builder builder = new AlertDialog.Builder(restituer_jeu.this);
                        builder.setTitle(msg);

                        builder.setMessage("Déposer le jeu ?");
                        builder.setCancelable(false);

                        builder.setPositiveButton("Oui", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                Toast.makeText(getApplicationContext(), "Jeu rendu, merci :) ", Toast.LENGTH_LONG).show();

                                // décalage de la listview qui commence à l'indice 0 alors que la DB est incrémentée de 1 en partant de ID = 1
                                String id = String.valueOf(position + 1);
                                new retour_jeu().execute(id);

                                // DB_Response.remove(position);
                                // notifyDataSetChanged();
                            }
                        });

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

                        builder.show();

                    }
                });

            }

            return rowView;

        }

    }

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

    class retour_jeu extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(restituer_jeu.this);
            pDialog.setMessage("Dépôt du jeu...mise à jour de la database");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args)
        {
            int success;

            try
            {

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                String position = args[0];
                params.add(new BasicNameValuePair("id", position));

                //String postReceiverUrl = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/test.php";
                JSONObject json = jsonParser.makeHttpRequest(url_restituer_emprunts, "POST", params);
                //JSONObject json = jsonParser.makeHttpRequest(url_update_product, "POST", params);

                // check your log for json response
                Log.d("Retour du jeu", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1)
                {
                    // modification de la DB avec une requête mysql
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about product deletion
                    setResult(100, i);
                    finish();
                }
            }

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

            return null;
        }

        protected void onPostExecute(String file_url)
        {
            pDialog.dismiss();
        }

    }

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


}