package com.example.patrice.rerservation01;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.patrice.rerservation01.imageutils.Utils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

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.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class edition_jeu extends AppCompatActivity
{
    private ListView lv;
    ArrayAdapter<String> adapter;
    EditText inputSearch;

    Button btn_supprimer, btn_scanner, btn_capture_image, btn_update;

    TextView tv_barcode;

    ImageView imageview_camera;

    JSONParser jsonParser = new JSONParser();

    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> jeux_liste;

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

    private static String url_requete_liste_jeux_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/request_all_games.php";
    private static String url_requete_infos_jeu = "http://analog-design.net/WORKAREA/WEBSITE/reservation/requete_infos_jeu.php";
    private static String url_admin_update_jeu_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/admin_update_jeu_db.php";
    private static String url_admin_supprime_jeu_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/admin_supprime_jeu_db.php";


    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_NAME = "nom";

    JSONArray jeux = null;

    EditText et_nom, et_description;

    String jeu_nom = null;

    Bitmap bitmap_image;


    private String barcode;
    private String filename;

    int request_capture_image = 150;

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

    private String retour = null;
    private String retour1 = null;
    private String retour2 = null;

    String listview_index;

    String listview_selection;

    String read_nom = null;
    String read_description = null ;
    String read_barcode = null;
    String read_image = null;

    String load_nom = null;          // 0
    String load_barcode = null;      // 1
    String load_description = null;  // 2
    String load_image = null;        // 3


    String change_image = "";

    private static final String TAG = "Download Task";


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

        jeux_liste = new ArrayList<HashMap<String, String>>();

        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        et_nom = (EditText) findViewById(R.id.et_nom);
        et_description = (EditText) findViewById(R.id.et_description);
        tv_barcode = (TextView) findViewById(R.id.tv_barcode);
        ImageView imageview_camera = (ImageView) findViewById(R.id.imageview_camera);
        btn_supprimer = (Button) findViewById(R.id.btn_supprimer);
        btn_scanner = (Button) findViewById(R.id.btn_scanner);
        btn_capture_image = (Button) findViewById(R.id.btn_capture_image);
        btn_update = (Button) findViewById(R.id.btn_update);

      //  inputSearch.addTextChangedListener(filterTextWatcher);

        btn_supprimer.setEnabled(false);

        new charge_liste_jeux_db().execute();

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                //Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();
                TextView val = (TextView) view.findViewById(R.id.product_name);

                listview_selection = val.getText().toString();

                //Toast.makeText(getApplicationContext(), "selected Item Name is "+ val.getText(), Toast.LENGTH_LONG).show();
                inputSearch.setText(val.getText());

                //
                int pos = position + 1;

                listview_index = String.valueOf(pos);

                String s1 = inputSearch.getText().toString();
                String s2 = val.getText().toString();


                if(s1.equals(s2))
                {
                    btn_supprimer.setEnabled(true); // champ nom nul
                }
                else // sinon on désactive
                {
                    btn_supprimer.setEnabled(false);
                }


                new requete_infos_jeu().execute(listview_index );


            }
        });

        inputSearch.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void onTextChanged(CharSequence cs, int start, int before, int count)
            {
                // When user changed the Text
                edition_jeu.this.adapter.getFilter().filter(cs);

                Button btn_supprimer = (Button) findViewById(R.id.btn_supprimer);

                String s1 = inputSearch.getText().toString();

                String s2 = listview_selection;


                //if(count != 0) // count
                if(s1.equals(s2))
                {
                    btn_supprimer.setEnabled(true); // champ nom nul
                }
                else // sinon on désactive
                {
                    btn_supprimer.setEnabled(false);
                }


            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
            {
            }

            @Override
            public void afterTextChanged(Editable arg0)
            {
            }
        });




        // création de la dialog box pour visualiser la boite du jeu
        final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

        imageview_camera = (ImageView) findViewById(R.id.imageview_camera);
        imageview_camera.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                View layout = inflater.inflate(R.layout.custom_fullimage_dialog, (ViewGroup) findViewById(R.id.layout_root));
                ImageView image = (ImageView) layout.findViewById(R.id.fullimage);

                try
                {
                    if(bitmap_image == null)
                    {
                        image.setImageResource(android.R.drawable.ic_menu_report_image);
                    }
                    else
                    {
                        image.setImageBitmap(bitmap_image);
                    }
                }
                catch (Exception e)
                {
                    image.setImageResource(android.R.drawable.ic_menu_report_image);
                }

                imageDialog.setIcon(android.R.drawable.btn_star_big_on);
                imageDialog.setTitle("Jeu : " + jeu_nom);
                imageDialog.setView(layout);

                imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                });

                imageDialog.create();
                imageDialog.show();

            }

        });


        btn_supprimer.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {

                Toast.makeText(edition_jeu.this, "Supprimer le jeu...", Toast.LENGTH_LONG).show();

                TextView val = (TextView) view.findViewById(R.id.product_name);
                et_nom = (EditText) findViewById(R.id.et_nom);
                //supprimer_dialog(listview_index, et_nom.getText().toString() );

                supprimer_dialog(listview_index, inputSearch.getText().toString() );


            }
        });

        btn_scanner.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {

                IntentIntegrator integrator = new IntentIntegrator(edition_jeu.this);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setOrientationLocked(true);
                integrator.setPrompt("Scan le code bar de la boîte de jeu");
                integrator.setCameraId(0);
                integrator.setBeepEnabled(false);
                //     integrator.setBarcodeImageEnabled(false);
                integrator.initiateScan();
            }
        });

        btn_capture_image.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Intent i;
                i = new Intent(getApplicationContext(), camera_capture_image.class);
                read_barcode = tv_barcode.getText().toString();
                i.putExtra("barcode", read_barcode);
                startActivityForResult(i, request_capture_image );

            }
        });

        btn_update.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
/*
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getApplicationContext());

                alertDialogBuilder.setTitle("Confirmation de l'update");

                alertDialogBuilder
                        .setMessage("Oui pour valider !")
                        .setCancelable(false)
                        .setPositiveButton("Oui",new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog,int id)
                            {
                                read_nom = et_nom.getText().toString();
                                read_description = et_description.getText().toString();
                                read_barcode = tv_barcode.getText().toString();

                                if(change_image.equals("")) // vide donc pas de changement
                                {
                                    read_image = load_image;
                                }
                                else
                                {
                                    // une nouvelle capture a eu lieu
                                    read_image = change_image;
                                }

                                // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                                //upload_image_to_server(read_image);
                                // effacer l'ancienne image ???? a prévoir

                                // 2) update par une requete mysql, on écrasse tous les champs
                                //update_database instance = new update_database();
                                //instance.execute(listview_index, read_nom, read_description, read_barcode, read_image);

                                Toast.makeText(edition_jeu.this, "Mise à jour réussi.", Toast.LENGTH_LONG).show();

                                //edition_jeu.this.finish();
                            }
                        })

                        .setNegativeButton("Non",new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog,int id)
                            {
                                dialog.cancel();
                            }
                        });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();

                */


/////

                mise_a_jour();
            }


        });

/*
                //Toast.makeText(edition_jeu.this, "Prévoir l'enregistrement...", Toast.LENGTH_LONG).show();

                read_nom = et_nom.getText().toString();
                read_description = et_description.getText().toString();
                read_barcode = tv_barcode.getText().toString();

                if(change_image.equals("")) // vide donc pas de changement
                {
                     read_image = load_image;
                }
                else
                {
                    // une nouvelle capture a eu lieu
                    read_image = change_image;
                }

                // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                //upload_image_to_server(read_image);
                // effacer l'ancienne image ???? a prévoir

                // 2) update par une requete mysql, on écrasse tous les champs
                //update_database instance = new update_database();
                //instance.execute(listview_index, read_nom, read_description, read_barcode, read_image);

            }
        });
*/
    }


/*
    private TextWatcher filterTextWatcher = new TextWatcher()
    {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

            Button btn_supprimer = (Button) findViewById(R.id.btn_supprimer);

            if(count != 0)
            {
                btn_supprimer.setEnabled(true); // champ nom nul
            }
            else // sinon on désactive
            {
                btn_supprimer.setEnabled(false);
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void afterTextChanged(Editable s)
        {

        }
    };

*/
    public boolean requete_database(String champ1, String valeur1, String champ2, String valeur2 )
    {

        boolean result;

        try
        {
            retour1 = new asynchrone_request_to_db().execute(champ1, valeur1).get();
            retour2 = new asynchrone_request_to_db().execute(champ2, valeur2).get();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        if(retour1.equals("existe") || retour2.equals("existe") )
        {
            result = false;
        }
        else
        {
            result = true;
        }

        return(result);

    }

    class asynchrone_request_to_db extends AsyncTask<String, String, String>
    {

        @Override
        protected void onPreExecute()
        {
            //super.onPreExecute();
        }

        protected String doInBackground(String... args)
        {

            String champ = args[0];
            String valeur = args[1];

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("champ", champ));
            params.add(new BasicNameValuePair("valeur", valeur));

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

            String reponse = null;

            try
            {
                //int success = json.getInt(TAG_SUCCESS);
                String msg =  json.getString("message");

                if (msg.equals("existe"))
                {
                    reponse = "existe";
                }

                else
                {
                    reponse = "vide";
                }
            }

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

            return reponse;
        }


        protected void onPostExecute()
        {
        }
    }


    protected void onActivityResult( int requestCode, int resultCode,  Intent data)
    {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        super.onActivityResult(requestCode, resultCode, data);

        if (result != null)
        {

            if (result.getContents() == null)
            {
                Log.d("-------", "Cancelled scan");
                Toast.makeText(this, "Pas de scan !.", Toast.LENGTH_LONG).show();
            }
            else
            {
                Log.d("-------", "Scanned");
                barcode = result.getContents();
                tv_barcode.setText(barcode);
            }
        }

        if(requestCode == request_capture_image)
        {
            filename = data.getStringExtra("TAG_FILENAME");

            if(filename.equals(""))
            {
                Toast.makeText(this, "Vide", Toast.LENGTH_LONG).show();
            }
            else
            {
                String path = Environment.getExternalStorageDirectory().getPath() + filename;
                change_image = path;

                //Bitmap bitmap = BitmapFactory.decodeFile(path); // Environment.getExternalStorageDirectory().getPath() + field_filename );
                //
                bitmap_image = BitmapFactory.decodeFile(path);
                ImageView imageview_camera = (ImageView) findViewById(R.id.imageview_camera);
                imageview_camera.setImageBitmap(bitmap_image);
            }
        }

    }

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

    class charge_liste_jeux_db extends AsyncTask<String, String, String[]>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        protected String[] doInBackground(String... args)
        {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject json = jParser.makeHttpRequest(url_requete_liste_jeux_db, "GET", params);

            Log.d("Tous les jeux: ", json.toString());

            String elements [] = null;

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

                if (success == 1)
                {
                    jeux = json.getJSONArray("liste_jeux_db");

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

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);

                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        jeux_liste.add(map);

                    }
                }
                else
                {
                    // vide , ce n'est pas prévu
                }
            }

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


            return null;
        }

        protected void onPostExecute(String tab [])
        {
            List<String> liste = new ArrayList<String>();

            for (int i=0;i<jeux_liste.size();i++)
            {
                HashMap<String, String> hashmap= jeux_liste.get(i);
                String nom = hashmap.get("nom");
                liste.add(nom);
            }

            // convertir arraylist en array
            String[] computers = liste.toArray(new String[liste.size()]);

            adapter = new ArrayAdapter<String>(edition_jeu.this, R.layout.search_list_item_layout, R.id.product_name, computers);
            lv.setAdapter(adapter);

        }
    }

    class requete_infos_jeu extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();

        }

        protected String doInBackground(String... args)
        {
            String id = args[0];

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

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


            String concate = null;

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

                if (success == 1)
                {
                    JSONArray productObj = json.getJSONArray("jeu");
                    // le premier element, car il y en a un seul !
                    JSONObject product = productObj.getJSONObject(0);

                    load_nom = product.getString("nom");
                    load_description = "blabla..."; //product.getString("description");
                    load_barcode = product.getString("barcode");
                    load_image = product.getString("image");

                    concate = load_nom + "&" + load_description + "&" + load_barcode + "&" + load_image;
                }

                else
                {
                    // erreur
                }
            }

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

            return(concate);
        }

        protected void onPostExecute(String s)
        {
            String[] parts = s.split("&");

            et_nom = (EditText) findViewById(R.id.et_nom);
            et_nom.setText(parts[0]);
            // passage variable globale
            jeu_nom = parts[0];


            et_description = (EditText) findViewById(R.id.et_description);
            et_description.setText(parts[1]);

            tv_barcode = (TextView) findViewById(R.id.tv_barcode);

            if(parts[2].equals("null")) {

                tv_barcode.setText("Barcode not define");
            }
            else
            {
                tv_barcode.setText(parts[2]);
            }

            DownloadTask downloadTask = new DownloadTask();
            //downloadTask.execute("http://analog-design.net/WORKAREA/WEBSITE/Codebar/caps.jpg");
            downloadTask.execute(parts[3]);


            downloading_file_task alpha = new downloading_file_task();
            alpha.execute(parts[3], parts[2] + ".jpeg" );

        }
    }

    private Bitmap downloadUrl(String strUrl) throws IOException
    {
        Bitmap bitmap=null;
        InputStream iStream = null;

        try
        {
            URL url = new URL(strUrl);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            /** Reading data from url */
            iStream = urlConnection.getInputStream();
            /** Creating a bitmap from the stream returned from the url */
            bitmap = BitmapFactory.decodeStream(iStream);
        }

        catch(Exception e)
        {
            Log.d("Exception url", e.toString());
        }

        finally
        {
            iStream.close();
        }

        return bitmap;
    }

    private class DownloadTask extends AsyncTask<String, Integer, Bitmap>
    {
        Bitmap bitmap = null;

        @Override
        protected Bitmap doInBackground(String... url)
        {
            try
            {
                bitmap = downloadUrl(url[0]);
            }

            catch(Exception e)
            {
                Log.d("Background Task",e.toString());
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap image)
        {
            ImageView imageview_camera = (ImageView) findViewById(R.id.imageview_camera);


            if(bitmap != null)
            {
                imageview_camera.setImageBitmap(image);
            }

            else
            {
                imageview_camera.setImageResource(R.drawable.image_missing_a);
            }

            // passage variable globale
            bitmap_image = image;
        }
    }

    /*********************************************************/
    public void upload_image_to_server(final String fichier_image)
    {

       // String file = Environment.getExternalStorageDirectory() + "/" + fichier_image ; //+ ".jpeg"; // avant jpeg
        String UrlServer = "http://analog-design.net/WORKAREA/WEBSITE/reservation/upload_multiple.php";
        new UploadFileAsync().execute(fichier_image, UrlServer);

    }

    //    Le type de l'information qui est nécessaire au traitement (dans l'exemple URL )
    //    Le type de l'information qui est passé à sa tâche pour indiquer sa progression (dans l'exemple : Integer )
    //    Le type de l'information passé au code lorsque la tâche est finie (dans l'exemple Long ).

    // Async Upload
    public class UploadFileAsync extends AsyncTask<String, Void, String>
    {

        String resServer;

        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params)
        {
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            int resCode = 0;
            String resMessage = "";

            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";

            String strSDPath = params[0];
            String strUrlServer = params[1];

            try
            {
                File file = new File(strSDPath);
                if(!file.exists())
                {
                    resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
                    return null;
                }

                FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

                URL url = new URL(strUrlServer);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setConnectTimeout(15000);
                conn.setReadTimeout(15000);

                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"fileUpload\";filename=\"" + strSDPath + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0)
                {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Response Code and  Message send by server (php script)
                resCode = conn.getResponseCode();
                if(resCode == HttpURLConnection.HTTP_OK)
                {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int read = 0;
                    while ((read = is.read()) != -1)
                    {
                        bos.write(read);
                    }

                    byte[] result = bos.toByteArray();
                    bos.close();

                    resMessage = new String(result);

                }

                Log.d("resCode=",Integer.toString(resCode));
                Log.d("resMessage=",resMessage.toString());

                fileInputStream.close();
                outputStream.flush();
                outputStream.close();

                resServer = resMessage.toString();


            }
            catch (Exception ex)
            {
                return null;
            }

            return (resServer); //null;
        }

        protected void onPostExecute (String resServer) //(Void unused)
        {
            reponse_serveur(resServer);
        }

    }

    // quand l'uploaid est fini
    protected void reponse_serveur(String resServer)
    {

        String strStatusID = "0";
        String strError = "Unknow Status!";

        Log.d("TRACE ************", " TRACE ");

        try
        {
            JSONObject c = new JSONObject(resServer);
            strStatusID = c.getString("StatusID");
            strError = c.getString("Error");
        }

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

        Log.d("RESPONSE ************", strStatusID.toString());


        if(strStatusID.equals("0"))
        {
            // FAIL
            Toast.makeText(this, "Transfert non réaliser !. ", Toast.LENGTH_LONG).show();
            Log.d(" FAIL ************", " FAIL ");

        }
        else
        {
            // OK
            Toast.makeText(this, "Upload réussi :) ", Toast.LENGTH_LONG).show();
            Log.d("SUCCESS ************", " Succes ");

        }

    }

    public class update_database extends AsyncTask<String, Void, String>
    {

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            //Toast.makeText(getApplicationContext(), "Début du traitement asynchrone", Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(String... args)
        {

            String id = args[0];
            String nom = args[1];
            String description = args[2];
            String barcode = args[3];
            String image = args[4];

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id", id));
            params.add(new BasicNameValuePair("nom", nom));
            params.add(new BasicNameValuePair("description", description));
            params.add(new BasicNameValuePair("barcode", barcode));
            params.add(new BasicNameValuePair("image", image));

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

            Log.d("Create Response", json.toString());

            String reponse = null;

            try
            {
                //int success = json.getInt(TAG_SUCCESS);
                String msg =  json.getString("success");

                if (msg.equals("OK"))
                {
                    reponse = "OK";
                }

                else
                {
                    reponse = "FAIL";
                }
            }

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

            return(reponse);

        }

        @Override
        protected void onPostExecute(String result)
        {
            if(result.equals("OK"))
            {
                Toast.makeText(getApplicationContext(), "Mise à jour des paramétres du jeu.", Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Erreur de traitement : Sauvegarde impossible !", Toast.LENGTH_LONG).show();
            }
        }
    }


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

    class supprime_jeu extends AsyncTask<String, String, String>
    {

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        protected String doInBackground(String... args)
        {

            String id = args[0];

            int success;
            String result = null;

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

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

                Log.d("Delete jeu", json.toString());

                success = json.getInt(TAG_SUCCESS);
                if (success == 1)
                {
                    //Intent i = getIntent();
                    //setResult(100, i);
                    //finish();
                    result = "OK";
                }
            }

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

            return result;
        }

        protected void onPostExecute(String result)
        {
            if(result.equals("OK"))
            {
                Toast.makeText(getApplicationContext(), "Le jeu vient d'être supprimer de la database.", Toast.LENGTH_LONG).show();
                adapter.notifyDataSetChanged();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Erreur de communication avec le serveur !", Toast.LENGTH_LONG).show();
            }

        }

    }


    protected void mise_a_jour()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(edition_jeu.this);
        builder.setTitle("Conformation:");
        builder.setIcon(R.drawable.update);
        String msg = "Voulez-vous mettre à jour les infos du  jeu ?.";
        builder.setMessage(msg)
                .setCancelable(false)

                .setPositiveButton("Oui", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        read_nom = et_nom.getText().toString();
                        read_description = et_description.getText().toString();
                        read_barcode = tv_barcode.getText().toString();

                        // test cas 1  OK  le barcode et l'image ne change pas

                        // test cas 2  OK
                       //read_barcode = "toto";

                        // test cas 3  OK

                        // test 4cas 4
                        read_barcode = "boufi";


                    /******************** cas 1 *********************************/
                        // no change
                        if( change_image.equals("") && load_barcode.equals(read_barcode))
                        {
                            String path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg" ;
                            String path_image_download_source = Environment.getExternalStorageDirectory() + "/Download/" + read_barcode + ".jpeg";

                            // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                            upload_image_to_server(path_image_download_source);

                            // 2) update par une requete mysql, on écrasse tous les champs
                            update_database instance = new update_database();
                            instance.execute(listview_index, read_nom, read_description, read_barcode, path_image_server);

                            Toast.makeText(edition_jeu.this, "Mise à jour réussi.", Toast.LENGTH_LONG).show();

                        }

                    /******************** cas 2 *********************************/

                        //  image unchange and barcode change
                        if( change_image.equals("") && !load_barcode.equals(read_barcode))
                        {
                            // extraire le nom du fichier qui se trouve dans le path load_image
                            String filename = load_image.substring(load_image.lastIndexOf("/")+1);

                            File old_file = new File(Environment.getExternalStorageDirectory() + "/Download/" + filename);
                            File new_file = new File(Environment.getExternalStorageDirectory() + "/Download/" + read_barcode + ".jpeg");

                            // renommer l'image
                            boolean success = old_file.renameTo(new_file);
                            if (!success)
                            {
                                System.out.println("Couldn't rename file!");
                            }
                            else
                            {
                                System.out.println("File renamed successfully!");
                            }

                            String path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg" ;
                            String path_image_download_source = Environment.getExternalStorageDirectory() + "/Download/" + read_barcode + ".jpeg";

                            // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                            upload_image_to_server(path_image_download_source);

                            // 2) update par une requete mysql, on écrasse tous les champs
                            update_database instance = new update_database();
                            instance.execute(listview_index, read_nom, read_description, read_barcode, path_image_server);

                            Toast.makeText(edition_jeu.this, "Mise à jour réussi.", Toast.LENGTH_LONG).show();
                        }

                    /*************** cas 3 **************************************/
                        //  image change and barcode unchange
                        if( !change_image.equals("") && load_barcode.equals(read_barcode))
                        {
                            String path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg" ;
                            //String path_image_download_source = Environment.getExternalStorageDirectory() + "/Download/" + read_barcode + ".jpeg";
                            String path_image_download_source = change_image;


                            // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                            upload_image_to_server(path_image_download_source);

                            // 2) update par une requete mysql, on écrasse tous les champs
                            update_database instance = new update_database();
                            instance.execute(listview_index, read_nom, read_description, read_barcode, path_image_server);

                            Toast.makeText(edition_jeu.this, "Mise à jour réussi.", Toast.LENGTH_LONG).show();
                        }

                    /***************** cas 4 ************************************/

                        //  image change and barcode change
                        if( !change_image.equals("") && !load_barcode.equals(read_barcode))
                        {
                            String filename = change_image.substring(change_image.lastIndexOf("/")+1);
                            String filename_less_extension = filename.substring(0, filename.lastIndexOf("."));

                            // nom image et barcode sont differents
                            if( !read_barcode.equals(filename_less_extension) )
                            {
                                File old_file = new File(change_image);
                                File new_file = new File(Environment.getExternalStorageDirectory() + "/" +read_barcode + ".jpeg");     ******* to debug

                                // renommer l'image
                                boolean success = old_file.renameTo(new_file);
                                if (!success)
                                {
                                    System.out.println("Couldn't rename file!");
                                }
                                else
                                {
                                    System.out.println("File renamed successfully!");
                                }

                                String path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg" ;
                                String path_image_download_source = Environment.getExternalStorageDirectory() +  read_barcode + ".jpeg";

                                // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                                upload_image_to_server(path_image_download_source);

                                // 2) update par une requete mysql, on écrasse tous les champs
                                update_database instance = new update_database();
                                instance.execute(listview_index, read_nom, read_description, read_barcode, path_image_server);

                                Toast.makeText(edition_jeu.this, "Mise à jour réussi.", Toast.LENGTH_LONG).show();
                            }

                            else
                            {
                                String path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg" ;
                                String path_image_download_source = Environment.getExternalStorageDirectory() +  read_barcode + ".jpeg";

                                // 1) copie l'image dans le répertoire du serveur, il s'agit de la mise à jours
                                upload_image_to_server(path_image_download_source);

                                // 2) update par une requete mysql, on écrasse tous les champs
                                update_database instance = new update_database();
                                instance.execute(listview_index, read_nom, read_description, read_barcode, path_image_server);

                                Toast.makeText(edition_jeu.this, "Mise à jour réussi.", Toast.LENGTH_LONG).show();

                            }

                        }

                    }
                })

                .setNegativeButton("Non",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        dialog.cancel();
                    }
                });

        AlertDialog  alertDialog = builder.create();
        alertDialog.show();

    }

    protected void supprimer_dialog(final String listview_index, String jeu_selection)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(edition_jeu.this);
        builder.setTitle("Conformation:");

        String msg = "Voulez-vous supprimer le jeu : \n" + listview_selection + " ?";

        builder.setMessage(msg)
                .setCancelable(false)

                .setPositiveButton("Oui", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        // supprime de la database mysql
                        supprime_jeu aqw = new supprime_jeu();
                        aqw.execute(listview_index);

                        // supprime de la liste
                        jeux_liste.remove( Integer.parseInt(listview_index) ); // supprime l'item qui est en selection
                        // recharge
                        adapter.notifyDataSetChanged();


                    }
                })

                .setNegativeButton("Non",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        dialog.cancel();
                    }
                });

        AlertDialog  alertDialog = builder.create();
        alertDialog.show();

    }


    //       http://velmm.com/download-image-from-url-to-sd-card-in/
    //        http://www.androhub.com/android-download-files-save/
    //        https://stackoverflow.com/questions/25785609/android-downloading-a-file-and-saving-on-sd-card?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
    //       https://www.avajava.com/tutorials/lessons/how-do-i-save-an-image-from-a-url-to-a-file.html
    //       https://stackoverflow.com/questions/21279838/android-get-a-file-from-http-and-store-in-sdcard?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
    //       http://www.codejava.net/java-se/networking/use-httpurlconnection-to-download-file-from-an-http-url

    private class downloading_file_task extends AsyncTask<String, Void, Void>
    {

        File repertoire = null;
        File outputFile = null;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... args)
        {

            String url_path = args[0];
            String downloadFileName = args[1];

            try
            {
                URL url = new URL(url_path);//Create Download URl
                HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
                c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
                c.connect();//connect the URL Connection

                //If Connection response is not OK then show Logs
                if (c.getResponseCode() != HttpURLConnection.HTTP_OK)
                {
                    Log.e(TAG, "Server returned HTTP " + c.getResponseCode()  + " " + c.getResponseMessage());
                }


                if (isSDCardPresent())
                {
                    repertoire = new File( Environment.getExternalStorageDirectory() + "/Download" );  //    + Utils.downloadDirectory);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
                }

                //If File is not present create directory
                /*if (!apkStorage.exists())
                {
                    apkStorage.mkdir();
                    Log.e(TAG, "Directory Created.");
                }*/

                outputFile = new File(repertoire, downloadFileName);//Create Output file in Main File

                //Create New File if not present
                if (!outputFile.exists())
                {
                    outputFile.createNewFile();
                    Log.e(TAG, "File Created");
                }

                FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
                InputStream is = c.getInputStream();//Get InputStream for connection

                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                while ((len1 = is.read(buffer)) != -1)
                {
                    fos.write(buffer, 0, len1);//Write new file
                }

                fos.close();
                is.close();

            }

            catch (Exception e)
            {
                e.printStackTrace();
                outputFile = null;
                Log.e(TAG, "Download Error Exception " + e.getMessage());
            }

            return null;
        }


        @Override
        protected void onPostExecute(Void result)
        {

            super.onPostExecute(result);
            //Toast.makeText(getApplicationContext(), "Fichier chargé avec succes.", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean isSDCardPresent()
    {
        if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED ))
        {
            return true;
        }

        return false;
    }

}