package com.example.patrice.reservation02;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
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.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class appairage_jeu_01 extends AppCompatActivity implements  SearchView.OnQueryTextListener
{
    Button btn_selection, btn_supprimer, btn_scanner, btn_capture_image, btn_update;
    TextView tv_barcode;
    ImageView imageview_camera;
    ListView listView;
    Appairage_Adapter adapter;
    SearchView search_view;
    JSONArray element = null;
    ArrayList<HashMap<String, String>> AppArrList = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String, String>> tempo = new ArrayList<HashMap<String, String>>();
    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

    private static String url_appairage_requete_liste_jeux_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/appairage_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";

    ArrayList<Listview_games> countrylist;
    JSONParser jParser = new JSONParser();
    String listview_index;

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

    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

    Bitmap bitmap_image;
    private static final String TAG = "Download Task";

    String change_image = "";
    String jeu_nom = null;
    String listview_selection;

    private String barcode;
    private String filename;

    int request_capture_image = 150;


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

        Toast.makeText(getApplicationContext(), "Debug on going ...", Toast.LENGTH_LONG).show();

        listView = (ListView) findViewById(R.id.listview_appairage);
        search_view = (SearchView) findViewById(R.id.search_view);

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


        try
        {
            tempo = new ProcessJSON().execute(url_appairage_requete_liste_jeux_db).get();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (ExecutionException e)
        {
            e.printStackTrace();
        }

        int nb_jeu = countrylist.size();

        getSupportActionBar().setTitle("  Appairage ");
        getSupportActionBar().setLogo(R.drawable.books);
//        getSupportActionBar().setDisplayShowHomeEnabled(true);
//        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        adapter = new Appairage_Adapter(getApplicationContext(), countrylist);
        listView.setAdapter(adapter);

        search_view.setOnQueryTextListener(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                TextView val = (TextView) view.findViewById(R.id.value);
                listview_selection = val.getText().toString();
                //inputSearch.setText(val.getText());
                search_view.setQuery(listview_selection, false);

                //int pos = position + 1;
                //listview_index = String.valueOf(pos);

                //String s1 = inputSearch.getText().toString();
                String s1 = search_view.getQuery().toString();

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

                if (s1.equals(s2)) {
                    //btn_selection.setEnabled(true);
                    btn_scanner.setEnabled(true);
                    btn_capture_image.setEnabled(true);
                    btn_update.setEnabled(true);
                    new requete_infos_jeu().execute(listview_selection);
                } else {
                    //btn_selection.setEnabled(false);
                    btn_scanner.setEnabled(false);
                    btn_capture_image.setEnabled(false);
                    btn_update.setEnabled(false);
                    tv_barcode.setText("xxxxxxxxxxxxx ?");
                    imageview_camera.setImageResource(R.drawable.image_missing_a);
                }
            }
        });

        // 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 : " + search_view.getQuery().toString());
                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)
            {
                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_selection);

            }
        });
*/
        btn_scanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                IntentIntegrator integrator = new IntentIntegrator(appairage_jeu_01.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 = null;

                read_barcode = tv_barcode.getText().toString();
                i = new Intent(getApplicationContext(), camera_capture_image.class); // camera_capture_image
                i.putExtra("barcode", read_barcode);
                startActivityForResult(i, request_capture_image);

                /*
                if(!read_barcode.equals(""))
                {
                    i = new Intent(getApplicationContext(), camera_capture_image.class);
                    i.putExtra("barcode", read_barcode);
                    startActivityForResult(i, request_capture_image);

                }
                else
                {
                    i = new Intent(getApplicationContext(), camera_capture_image.class);
                    i.putExtra("barcode", barcode);
                    startActivityForResult(i, request_capture_image);
                }
               */


            }
        });

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

                mise_a_jour();
            }


        });

    }

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

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

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

    public boolean onQueryTextChange(String newText)
    {
        adapter.getFilter().filter(newText);

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

        if (s1.equals(s2)) {
 //           btn_selection.setEnabled(true);
            btn_scanner.setEnabled(true);
            btn_capture_image.setEnabled(true);
            btn_update.setEnabled(true);
            new requete_infos_jeu().execute(listview_selection);
        } else {
//            btn_selection.setEnabled(false);
            btn_scanner.setEnabled(false);
            btn_capture_image.setEnabled(false);
            btn_update.setEnabled(false);
            tv_barcode.setText("xxxxxxxxxxxxx ?");
            imageview_camera.setImageResource(R.drawable.image_missing_a);

        }


        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query)
    {
        return false;
    }


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

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

    }


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


    private class ProcessJSON extends AsyncTask<String, Void, ArrayList>
    {

        @Override
        protected void onPreExecute()
        {
        }

        @Override
        protected ArrayList doInBackground(String... strings)
        {
            String stream = null;
            String urlString = strings[0];

            newHTTPDataHandler hh = new newHTTPDataHandler();
            stream = hh.GetHTTPData(urlString);

            try
            {
                JSONObject jObj = null;
                jObj = new JSONObject(stream);
                element = jObj.getJSONArray("liste_jeux_db");

                countrylist = new ArrayList<Listview_games>();

                for (int i = 0; i < element.length(); i++)
                {
                    JSONObject x = element.getJSONObject(i);

                    String id = x.getString("id");
                    String nom =  x.getString("nom");
                    String appairage = x.getString("appairage");

                    Listview_games country = new Listview_games(id, nom, "image", "barcode", "statut", "emprunteur", appairage);
                    countrylist.add(country);

                }


            }

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


            return AppArrList; // a voir

        }

        @Override
        protected void onPostExecute(final ArrayList data)
        {

        }

    }

    class newHTTPDataHandler
    {
        String stream = null;

        public newHTTPDataHandler()
        {
        }

        public String GetHTTPData(String urlString)
        {
            try
            {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Check the connection status
                if(urlConnection.getResponseCode() == 200)
                {
                    // if response code = 200 ok
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                    // Read the BufferedInputStream
                    BufferedReader r = new BufferedReader(new InputStreamReader(in));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null)
                    {
                        sb.append(line);
                    }
                    stream = sb.toString();
                    // End reading...............

                    // Disconnect the HttpURLConnection
                    urlConnection.disconnect();
                }
                else
                {
                    // Do something
                }
            }

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

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

            finally
            {

            }

            // Return the data from specified url
            return stream;
        }
    }


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

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

        }

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

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

            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_barcode + "&" + load_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 tmp = s;

            String[] parts = tmp.split("&");
            tv_barcode = (TextView) findViewById(R.id.tv_barcode);

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

                tv_barcode.setText("xxxxxxxxxxxxx ?");
            } 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 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) {

                int newHeight = 200; // New height in pixels
                int newWidth = 200; // New width in pixels

                //imageview_camera.requestLayout();


             //   int width = imageview_camera.getWidth();
            //    int height = imageview_camera.getHeight();
/*

                int currentBitmapWidth = image.getWidth();
                int currentBitmapHeight = image.getHeight();

                int ivWidth = imageview_camera.getWidth();
                int ivHeight = imageview_camera.getHeight();

                int aanewWidth = ivWidth;

                newHeight = (int) Math.floor((double) currentBitmapHeight *( (double) aanewWidth / (double) currentBitmapWidth));

                Bitmap newbitMap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

                imageview_camera.setImageBitmap(newbitMap);
*/



                int srcWidth = image.getWidth();
                int srcHeight = image.getHeight();
                int dstWidth = (int)(srcWidth*0.6f);
                int dstHeight = (int)(srcHeight*0.6f);
                Bitmap dstBitmap = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, true);
                imageview_camera.setImageBitmap(dstBitmap);

                // Apply the new height for ImageView programmatically
                //imageview_camera.getLayoutParams().height = newHeight;

                // Apply the new width for ImageView programmatically
                //imageview_camera.getLayoutParams().width = newWidth;

                // Set the scale type for ImageView image scaling
              //  imageview_camera.setScaleType(ImageView.ScaleType.CENTER_CROP); // FIT_XY

              //  imageview_camera.setImageBitmap(image);



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

            // passage variable globale
            bitmap_image = image;
        }
    }

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

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

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

    protected void mise_a_jour()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(appairage_jeu_01.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 = search_view.getQuery().toString();
                        read_description = "zsx"; //et_description.getText().toString();
                        read_barcode = tv_barcode.getText().toString();
                        String defaut_barcode = "xxxxxxxxxxxxx ?";

                        if( (bitmap_image == null) || read_barcode.equals(defaut_barcode) )
                        {
                            Toast.makeText(getApplicationContext(), "Enregistrement impossible: " + "\n" +"Le barcode et la capture sont obligatoire !", Toast.LENGTH_LONG).show();
                        }

                        else
                        {
                            //  bitmap_image.
                            //  imageview_camera.

                            String path_image_server = "";
                            String path_image_download_source = "";
                            update_database instance = new update_database();
        /*
                                path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg";
                                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
                                instance.execute(read_nom, read_description, read_barcode, path_image_server);
        */

                            //  read_barcode = "dindon";


                            /******************** cas 1 *********************************/
                            // no change
                            if (change_image.equals("") && load_barcode.equals(read_barcode)) {
                                Toast.makeText(getApplicationContext(), "Pas de changement !.", Toast.LENGTH_LONG).show();
                            }


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

                            //  image unchange and barcode change
                            if (change_image.equals("") && !load_barcode.equals(read_barcode)) {

                                // sauve le bitmpa contenu dans imageview_camera sous le nouveau barcode
                                BitmapDrawable draw = (BitmapDrawable) imageview_camera.getDrawable();
                                Bitmap bitmap = draw.getBitmap();
                                FileOutputStream outStream = null;
                                File creation_file = new File(Environment.getExternalStorageDirectory() + "/" + read_barcode + ".jpeg");

                                try {
                                    outStream = new FileOutputStream(creation_file);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                                    outStream.flush();
                                    outStream.close();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg";
                                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
                                instance.execute(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)) {
                                //path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg" ;
                                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
                                //instance.execute(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)) {
                                path_image_server = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + read_barcode + ".jpeg";
                                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
                                instance.execute(read_nom, read_description, read_barcode, path_image_server);

                            }

                            // int indice = Integer.parseInt(listview_index);
                            //indice = indice - 1; // la liste commence à 0
                            //countrylist.get(indice).setBarcode(read_barcode);
                            //countrylist.get(indice).setImage(path_image_server);
                            //countrylist.get(indice).setAppairage("OK");

                            //adapter.notifyDataSetChanged();

                        }

                    }
                })

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

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

    }

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

    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[0];
            String description = args[1];
            String barcode = args[2];
            String image = args[3];

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

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

}
