package com.example.patrice.rerservation01;

import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
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.ArrayAdapter;
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;


// ALTER TABLE appli_table_jeu ADD emprunteur VARCHAR(30) AFTER statut;

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_jeu.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";
    public static final String key_position_gps = "position_ONsemi";

    String nom_uilisateur = "";
    String position_gps = "";

    boolean debug_mode = true;

    private String[] affiche_message = new String[]{   "Aucun jeu n'a été emprunté"   };

    @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);
        position_gps = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_position_gps, null);


        if (Build.BRAND.equalsIgnoreCase("generic"))
        {
            // emulator
            position_gps = "inside";
        }
        else
        {
            // device
        }

        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.v("Affiche format JSON: ", json.toString());

            String flag_restituer = "";

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

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

                    flag_restituer = "OK";

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

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

                if (success == 0)
                {
                    flag_restituer = "NONE";
                }
            }

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

            return flag_restituer;

        }

        protected void onPostExecute(String flag_restituer)
        {

            pDialog.dismiss();

            // https://www.myandroidsolutions.com/2014/09/25/listview-empty-message/#.Wu85pH_Licw
            // http://tutos-android-france.com/listview-afficher-une-liste-delements/
           // si aucun retour JSON alors pas de jeu

            lv = (ListView)findViewById(R.id.lv_emprunts);

            if( flag_restituer.equals("OK") )
            {
                instance_listview_adapter = new liste_restitution_adapter(DB_Response, restituer_jeu.this);
                lv.setAdapter(instance_listview_adapter);
            }
            else
            {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(restituer_jeu.this, android.R.layout.simple_list_item_1, affiche_message);
                lv.setDivider(null); // divider ou separator non visible
                lv.setAdapter(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( 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);

                if(!position_gps.equals("inside"))  // condition pour rendre le jeu
                {
                    btn_delete.setClickable(true);

                    btn_delete.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {

                            AlertDialog.Builder builder = new AlertDialog.Builder(restituer_jeu.this);
                            String msg = "Attention :";
                            builder.setTitle(msg);

                            View line = new View(context);
                            line.setBackgroundColor(0xFF00FF00);

                            //builder.setView();  setDividerColor("#FF00FF").
                            builder.setMessage("Vous devez être sur le site de ONsemi pour valider la restitution du jeu !");
                            builder.setCancelable(false);

                            builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    dialog.cancel();

                                }
                            });

                            builder.show();

                        }
                    });
                }

                else
                {
                    btn_delete.setClickable(true);

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

                                    // 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 id = DB_Response.get(position).getId();  // position dans la table , c'est à dir l'indice qui est l'on incrémente

                                    //verifier si une notification existe ? si oui on l'efface'

                                    String jeu = elements_liste.get(position).getJeu();

                                    new retour_jeu().execute(id, jeu);

                                    // 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
            {
                String position = args[0];
                String jeu = args[1];

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", position));
                params.add(new BasicNameValuePair("jeu", jeu));

                JSONObject json = jsonParser.makeHttpRequest(url_restituer_emprunts, "POST", params);

                Log.v("Retour du jeu", json.toString());

                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 s)
        {
            pDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Jeu rendu, merci :) ", Toast.LENGTH_LONG).show();

            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
            mNotificationManager.cancelAll();

            finish();
        }

    }

    /*************************************************************************/
/*
    private void clearNotification(int notification_id){
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
        mNotificationManager.cancel(notification_id);
    }

    /*************************************************************************/
/*
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
   mNotificationManager.cancelAll();
*/

}