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;

// https://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/

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

    Button btn_selection, 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;


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

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

        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        btn_selection = (Button) findViewById(R.id.btn_selection);
        tv_barcode = (TextView) findViewById(R.id.tv_barcode);
        imageview_camera = (ImageView) findViewById(R.id.imageview_camera);
        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);

        /* defaut */
        btn_selection.setEnabled(false);
        btn_scanner.setEnabled(false);
        btn_capture_image.setEnabled(false);
        btn_update.setEnabled(false);

        /* chargement */
        new charge_liste_jeux_db().execute();

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                TextView val = (TextView) view.findViewById(R.id.product_name);
                listview_selection = val.getText().toString();
                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_selection.setEnabled(true);
                }
                else
                {
                    btn_selection.setEnabled(false);
                    btn_scanner.setEnabled(false);
                    btn_capture_image.setEnabled(false);
                    btn_update.setEnabled(false);
                    tv_barcode.setText("xxxxxxxxxxxxxx ?");
                    imageview_camera.setImageResource(R.drawable.image_missing_a);
                }
            }
        });

        inputSearch.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void onTextChanged(CharSequence cs, int start, int before, int count)
            {
                edition_jeu_02.this.adapter.getFilter().filter(cs);

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

                if(s1.equals(s2))
                {
                    btn_selection.setEnabled(true);
                }
                else
                {
                    btn_selection.setEnabled(false);
                    btn_selection.setEnabled(false);
                    btn_scanner.setEnabled(false);
                    btn_capture_image.setEnabled(false);
                    btn_update.setEnabled(false);
                    tv_barcode.setText("xxxxxxxxxxxxxx ?");
                    imageview_camera.setImageResource(R.drawable.image_missing_a);

                }
            }

            @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.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_selection.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(edition_jeu_02.this, "Selection", Toast.LENGTH_LONG).show();

                btn_scanner.setEnabled(true);
                btn_capture_image.setEnabled(true);
                btn_update.setEnabled(true);
                // récupére les datas que l'on veut affichier
                new requete_infos_jeu().execute(listview_index );

            }
        });

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

                IntentIntegrator integrator = new IntentIntegrator(edition_jeu_02.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_02.class);
                read_barcode = tv_barcode.getText().toString();
                i.putExtra("barcode", "0000");
                startActivityForResult(i, request_capture_image );

            }
        });

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

                mise_a_jour();
            }


        });


    }

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

    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_02.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 non prévu
                }
            }

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

            return(concate);
        }

        protected void onPostExecute(String s)
        {
            String[] parts = s.split("&");
            tv_barcode = (TextView) findViewById(R.id.tv_barcode);

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

                tv_barcode.setText("xxxxxxxxxxxxxx ?");
            }
            else
            {
                tv_barcode.setText(parts[2]);
            }

            DownloadTask downloadTask = new DownloadTask();

            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

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

            String path_image_download_source = Environment.getExternalStorageDirectory() + "/Download/" + read_barcode + ".jpeg";

            File file = new File(  path_image_download_source );
            file.delete();

        }

    }

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

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

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

        @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("1"))
                {
                    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();
            }
        }
    }

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

    protected void mise_a_jour()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(edition_jeu_02.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 = inputSearch.getText().toString();
                        //read_nom = "aqw";// et_nom.getText().toString();
                        read_description = "zsx"; //et_description.getText().toString();
                        read_barcode = "747"; //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);

                        }

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

                        }

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

                        }

                        /***************** 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_02.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);

                            }

                        }

                    }
                })

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

    }

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

        return false;
    }

}