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.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
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.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.example.patrice.rerservation01.R.id.pid;

// https://github.com/niravkalola/ListViewDemo/tree/master/app/src/main/java/com/nkdroid/listview/demo

public class mes_emprunts04 extends AppCompatActivity
{
    private ListView lv;
    private MyAppAdapter myAppAdapter;

    //private ArrayList<ProfileModel02> profileModelArrayList;

    private ArrayList<Jeu_Listing> DB_Response;     // profileModelArrayList;

    private ProgressDialog pDialog;

    JSONParser jParser = new JSONParser();

//    private static String url_jeu = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/mes_emprunts.php";
    private static String url_jeu = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/requete_emprunts.php";

    private static String url_retour = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/requete_retour_jeu.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_ID = "id";
    private static final String TAG_JEU = "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 products = null;

    public static final String key_nom_utilisateur = "nom_utilisateur";

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

        String 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 chargement_infos_DB().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 chargement_infos_DB extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(mes_emprunts04.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"));
            JSONObject json = jParser.makeHttpRequest(url_jeu, "GET", params);
            Log.d("Affiche format JSON: ", json.toString());

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

                if (success == 1)
                {
                    // games found
                    products = json.getJSONArray(TAG_PRODUCTS);

                    DB_Response = new ArrayList<>();

                    // looping
                    for (int i = 0; i < products.length(); i++)
                    {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String jeu = c.getString(TAG_JEU);
                        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(id, jeu ,statut, date_retrait, time_retrait, date_retour, time_retour ));
                        //profileModelArrayList.add(new ProfileModel02("Surabhi","India",R.drawable.games));
                        //profileModelArrayList.add(new ProfileModel02("Martins","Nigeria",R.drawable.games));
                    }
                }

                else
                {
                    // pas de jeu dans l'histoirque
                }
            }

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

            return null;
        }

        protected void onPostExecute(String file_url)
        {

            pDialog.dismiss();

            // updating UI from Background Thread
            runOnUiThread(new Runnable()
            {
                public void run()
                {
                    lv = (ListView)findViewById(R.id.lv_emprunts);
                    myAppAdapter = new MyAppAdapter(DB_Response, mes_emprunts04.this);
                    lv.setAdapter(myAppAdapter);
                }
            });
        }
    }

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

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

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

            try
            {

                //postText();

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


          //      params.add(new BasicNameValuePair(TAG_JEU, "name"));
          //      params.add(new BasicNameValuePair(TAG_DATE_RETOUR, "price"));
          //      params.add(new BasicNameValuePair(TAG_DATE_RETOUR, "description"));


                // List<NameValuePair> params = new ArrayList<NameValuePair>();
               // params.add(new BasicNameValuePair(TAG_PID, pid));

                // getting product details by making HTTP request
                String postReceiverUrl = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/test.php";
                JSONObject json = jsonParser.makeHttpRequest(postReceiverUrl, "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();
        }

    }

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

    private void postText(){
        try{
            // url where the data will be posted
            String postReceiverUrl = "http://analog-design.net/WORKAREA/WEBSITE/Mysql/test.php";
                                    //http://analog-design.net/WORKAREA/WEBSITE/Mysql/test.php
            Log.v("TAG" , "postURL: " + postReceiverUrl);

            // HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // post header
            HttpPost httpPost = new HttpPost(postReceiverUrl);

            // add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "6"));
            //nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
            //nameValuePairs.add(new BasicNameValuePair("email", "mike@testmail.com"));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // execute HTTP post request
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null)
            {
                String responseStr = EntityUtils.toString(resEntity).trim();
                Log.v("TAG", "Response: " +  responseStr);

                // you can add an if statement here and do other actions based on the response
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /************************************************************************/
/*
    class SaveProductDetails extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProductActivity.this);
            pDialog.setMessage("Saving product ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args)
        {

            // getting updated data from EditTexts
            String name = txtName.getText().toString();
            String price = txtPrice.getText().toString();
            String description = txtDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_PID, pid));
            params.add(new BasicNameValuePair(TAG_NAME, name));
            params.add(new BasicNameValuePair(TAG_PRICE, price));
            params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));

            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_product, "POST", params);

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

                if (success == 1)
                {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                }
                else
                {
                    // failed to update product
                }
            }

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

            return null;
        }
/*
        /**
         * After completing background task Dismiss the progress dialog
         * **/
/*        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product uupdated
            pDialog.dismiss();
        }
    }
*/

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

    public class MyAppAdapter extends BaseAdapter
    {

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

        //public ArrayList<ProfileModel02> profileList;
        public ArrayList<Jeu_Listing> elements_liste; //profileList;

        public Context context;

        //private MyAppAdapter(ArrayList<ProfileModel02> apps, Context context)
        private MyAppAdapter(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);  //item_profile01

                // configure view holder
                viewHolder = new ViewHolder();

                //viewHolder.profilePic = (ImageView) rowView.findViewById(R.id.imgProfile);
                //viewHolder.username = (TextView) rowView.findViewById(R.id.txtUsername);
                //viewHolder.country = (TextView) rowView.findViewById(R.id.txtCountry);
                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()+"");

            viewHolder.id.setText(elements_liste.get(position).getId() + "" );
            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);

            /******/

            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(mes_emprunts04.this);
                            //   builder.setTitle("Restitution du jeu emprunter !");
                            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);
                                    //String coco = "3";
                                    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 ProfileModel02
{

    private String username;
    private String country;
    private int profilePic;

    String id;
    String jeu;
    String date;
    String time;

    /*public ProfileModel02(String username, String country, int profilePic)
    {
        this.username = username;
        this.country = country;
        this.profilePic = profilePic;
    }*/
/*
    public ProfileModel02 (String id, String jeu, String date, String time)
    {
        this.id = id;
        this.jeu = jeu;
        this.date = date;
        this.time = time;
    }

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

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    /*************************/
/*
    public String getCountry()
    {
        return country;
    }

    public void setCountry(String country)
    {
        this.country = country;
    }

    /*************************/
/*
    public int getProfilePic()
    {
        return profilePic;
    }

    public void setProfilePic(int profilePic)
    {
        this.profilePic = profilePic;
    }

    /*************************/
/*
    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    /*****************************/
/*
    public String getJeu()
    {
        return jeu;
    }

    public void setJeu(String jeu)
    {
        this.jeu = jeu;
    }

    /*****************************/
/*
    public String getDate()
    {
        return date;
    }

    public void setDate(String date)
    {
        this.date = date;
    }

    /*****************************/
/*
    public String getTime()
    {
        return time;
    }

    public void setTime(String time)
    {
        this.time = time;
    }

}
*/

class Jeu_Listing
{

    String id;
    String jeu;
    String statut;
    String date_retrait;
    String time_retrait;
    String date_retour;
    String time_retour;

    public Jeu_Listing (String id, String jeu, String statut, String date_retrait, String time_retrait, String date_retour, String time_retour)
    {
        this.id = id;
        this.jeu = jeu;
        this.statut = statut;
        this.date_retrait = date_retrait;
        this.time_retrait = time_retrait;
        this.date_retour = date_retour;
        this.time_retour = time_retour;

    }


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

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

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

    public String getJeu()
    {
        return jeu;
    }

    public void setJeu(String jeu)
    {
        this.jeu = jeu;
    }

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

    public String getStatut()
    {
        return statut;
    }

    public void setStatut(String statut)
    {
        this.statut = statut;
    }


    public String getDateRetrait()
    {
        return date_retrait;
    }

    public void setDate(String date_retrait)
    {
        this.date_retrait = date_retrait;
    }

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

    public String getTimeRetrait()
    {
        return time_retrait;
    }

    public void setTime(String time_retrait)
    {
        this.time_retrait = time_retrait;
    }

    public String getDateRetour()
    {
        return date_retour;
    }

    public String getTimeRetour()
    {
        return time_retour;
    }

}
