package com.example.patrice.rerservation01.config_options;

import android.app.ProgressDialog;
import android.content.Intent;
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.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.patrice.rerservation01.JSONParser;
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;

import com.example.patrice.rerservation01.R;
import com.example.patrice.rerservation01.camera_capture_image;

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


public class ajouter_jeu extends AppCompatActivity
{
    JSONParser jsonParser = new JSONParser();

    private ProgressDialog pDialog;

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

    //ALTER TABLE contacts ADD email VARCHAR(60) AFTER name;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    EditText et_nom, et_description;
    TextView tv_barcode;
    Button btn_scanner, btn_capture_image, btn_enregistre;
    ImageView imageview_camera;

    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;


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

        getSupportActionBar().setTitle("Ajouter un jeu");
        getSupportActionBar().setLogo(R.drawable.plus);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        et_nom = (EditText) findViewById(R.id.et_nom);
        et_description = (EditText) findViewById(R.id.et_description);
        tv_barcode = (TextView) findViewById(R.id.tv_barcode);

        Button btn_scanner = (Button) findViewById(R.id.btn_scanner);
        Button btn_capture_image = (Button) findViewById(R.id.btn_capture_image);
        Button btn_enregistre = (Button) findViewById(R.id.btn_enregistre);
        ImageView imageview_camera = (ImageView) findViewById(R.id.imageview_camera);

        et_nom.addTextChangedListener(filterTextWatcher);

        // voir traitement_03 pour l'implémentation

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

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

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

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

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

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

                //String nom = et_nom.getText().toString();
                //String description = et_description.getText().toString();

                //String barcode = "1234567890";
                //String image = "http://analog-design.net/WORKAREA/WEBSITE/reservation/IMG/MET-ART_LND_191_0004.jpg";


                String nom = "pluto";
                String barcode = "555";
                String description = "bof";

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

                BigCalcul calcul = new BigCalcul();
                calcul.execute(nom, description, barcode, image_store_path);
/*
                boolean result = requete_database("nom", nom,  "barcode", barcode);

                if(result == false)
                {
                    Toast.makeText(getApplicationContext(), "Le jeu exite déjà dans la database !.", Toast.LENGTH_LONG).show();
                }

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


                    // 2) update par une requete mysql

                    Toast.makeText(getApplicationContext(), "Ajout.", Toast.LENGTH_LONG).show();

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

                   //  new ajouter_jeu_db().execute(nom, description, barcode, image_store_path);

                    BigCalcul calcul = new BigCalcul();
                    calcul.execute();


                }
*/
            }
        });
    }

    private TextWatcher filterTextWatcher = new TextWatcher()
    {

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

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

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

        }

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

        }

        @Override
        public void afterTextChanged(Editable s)
        {

        }
    };

    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);
                Button btn_capture_image = (Button) findViewById(R.id.btn_capture_image);
                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
            {
                String path = Environment.getExternalStorageDirectory().getPath() + filename;
                Bitmap bitmap = BitmapFactory.decodeFile(path); // Environment.getExternalStorageDirectory().getPath() + field_filename );
                ImageView imageview_camera = (ImageView) findViewById(R.id.imageview_camera);
                imageview_camera.setImageBitmap(bitmap);
                Button btn_enregistre = (Button) findViewById(R.id.btn_enregistre);
                btn_enregistre.setEnabled(true);
            }
        }

    }

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

    // pour le retour - inclus dans l'action bar ( < )
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

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

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

        protected String doInBackground(String... args)
        {
            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("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_ajouter_jeu_db,  "POST", params);

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

            String res = "";

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



                if (success == 1)
                {
                    res = "OK";
                }
                else
                {
                    res = "FAIL";
                }
            }

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

            return(res);
        }

        protected void onPostExecute(String res)
        {
            pDialog.dismiss();

            if(res.equals("OK"))
            {
                Toast.makeText(getApplicationContext(), "Mise à jour réussi. ", Toast.LENGTH_LONG).show();
            }

        }

    }

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

        boolean result;

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

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

        return(result);

    }

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

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

        protected String doInBackground(String... args)
        {

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

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

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

            String reponse = null;

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

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

                else
                {
                    reponse = "vide";
                }
            }

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

            return reponse;
        }


        protected void onPostExecute()
        {
        }
    }


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

        }

    }


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

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            Toast.makeText(getApplicationContext(), "Début du traitement asynchrone", Toast.LENGTH_LONG).show();
        }
/*
        @Override
        protected void onProgressUpdate(Integer... values)
        {
            super.onProgressUpdate(values);
            // Mise à jour de la ProgressBar
            //mProgressBar.setProgress(values[0]);
        }
*/
        @Override
        protected String doInBackground(String... args)
        {

            String alpha = "a";

            /*int progress;
            for (progress=0;progress<=100;progress++)
            {
                for (int i=0; i<1000000; i++){}
                //la méthode publishProgress met à jour l'interface en invoquant la méthode onProgressUpdate
                //publishProgress(progress);
                progress++;
            }*/

            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("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_ajouter_jeu_db,  "POST", params);

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

            String reponse = null;

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

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

                else
                {
                    reponse = "FAIL";
                }
            }

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

            return(reponse);

        }

        @Override
        protected void onPostExecute(String result)
        {
            if(result.equals("OK"))
            {
                Toast.makeText(getApplicationContext(), "Sauvegarde dans la base des jeux.", Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Erreur de communication avec le serveur !", Toast.LENGTH_LONG).show();
            }
        }
    }
}