package com.example.patrice.rerservation01;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class traitement_02 extends AppCompatActivity
{

    //private Button button;
    //private TextView tv_nom_jeu;
    private TextView tv_barcode, tv_titre_jeu;
    //private TextView tv_image_barcode;


    Button btn_capture_image;
    Button btn_save_to_DB;
    ImageView simpleImageView, imageview_camera;

    Button btn_search,btn_capture, btn_enregistre;

    int request_saisir_nom = 125;
    int request_capture_image = 150;

    private String filename;
    private String game_name;

    private String retour = null;
    private String barcode = null;


    JSONParser jsonParser = new JSONParser();

    //    private static String url_update_jeu =  "http://analog-design.net/WORKAREA/WEBSITE/reservation/mise_a_jour_jeu_DB_mysql.php";
    private static String url_update_jeu =  "http://analog-design.net/WORKAREA/WEBSITE/reservation/update_request.php";

    private static final String TAG_SUCCESS = "success";

    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String GAME_NAME = "game_name";

    SharedPreferences sharedpreferences;

    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.traitement_02_layout);

        /* action barre */
        ActionBar actionBar = getSupportActionBar(); // or getActionBar();
        getSupportActionBar().setTitle("Insertion du jeu dans DB"); // set the top title

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        // widget

        btn_search = (Button) findViewById(R.id.btn_search);
        btn_capture_image =(Button) findViewById(R.id.btn_capture_image);
        btn_enregistre =(Button) findViewById(R.id.btn_enregistre);

        btn_capture_image.setEnabled(false);
        btn_enregistre.setEnabled(false);

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

        imageview_camera = (ImageView) findViewById(R.id.imageview_camera);

        /// passage des paramétres
        Intent intent = getIntent();
        Bundle b = getIntent().getExtras();
        barcode = b.getString("barcode", "");

        String affichage = "Barcode scan : " + barcode;
        tv_barcode.setText(affichage);

        btn_search.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                Intent i = new Intent(getApplicationContext(), search_jeu_listview.class);
                startActivityForResult(i, request_saisir_nom );
            }
        });

        btn_capture_image.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i;
                i = new Intent(getApplicationContext(), camera_capture_image.class);
                //String field_code = id_class.getCode();
                i.putExtra("barcode", barcode);
                startActivityForResult(i, request_capture_image );

            }
        });


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

                // 1) copie l'image dans le répertoire du serveur
                filename = filename.replace("/","");
                upload_image_to_server(filename);

                // 2) update par une requete mysql

                try
                {
                    //

                    //String nom = game_name;
                    //game_name = "A l'abordage ! - Der schwarze pirat";
                   // filename = "7622210713803.jpeg";

                    String image_store_path = "http://analog-design.net/WORKAREA/WEBSITE/reservation/Capture/" + filename ;
                    //String barcode = "987654321";

                    retour = new update_jeu().execute(game_name , image_store_path, barcode ).get();

                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                catch (ExecutionException e)
                {
                    e.printStackTrace();
                }

                if (retour.equals("OK"))
                {
                    Toast.makeText(getApplicationContext(), "Mise à jour réussi. ", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Erreur pendant la mise à jour !.", Toast.LENGTH_LONG).show();
                }


                Toast.makeText(getApplicationContext(), "Mode debug. ", Toast.LENGTH_LONG).show();

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);


        if(requestCode == request_saisir_nom)
        {
            game_name = data.getStringExtra("TAG_NAME");
            tv_titre_jeu.setText(game_name);
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(GAME_NAME, game_name);
            editor.commit();

            btn_capture_image.setEnabled(true);
        }

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

            if(filename.equals(""))
            {
                Toast.makeText(this, "Vide", Toast.LENGTH_LONG).show();
            }
            else
            {

                //tv_image_barcode.setText(filename);

                String path = Environment.getExternalStorageDirectory().getPath() + filename;

                Bitmap bitmap = BitmapFactory.decodeFile(path); // Environment.getExternalStorageDirectory().getPath() + field_filename );
                imageview_camera.setImageBitmap(bitmap);
                btn_enregistre.setEnabled(true);

                //id_class.setFilename(path);
                //btn_enregistre.setEnabled(true);
            }

        }

    }


    /*********************************************************/
    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(file, 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 ");

        }

    }

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

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

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

        protected String doInBackground(String... args)
        {

            String nom = args[0];
            String image = args[1];
            String barcode = args[2];

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

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

            String reponse = null;

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

                if (success == 1)
                {
                    //Toast.makeText(gestion_DB02.this, "Ajout réussi. ", Toast.LENGTH_LONG).show();
                    reponse = "OK";
                }

                else
                {
                    // fail
                    // Toast.makeText(gestion_DB02.this, "Erreur pendant l'enregistrement !.", Toast.LENGTH_LONG).show();
                    reponse = "FAIL";
                }
            }

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

            return reponse; //null;//return null;
        }


        protected void onPostExecute(String file_url)
        {
        }
    }

}
