package com.example.patrice.rerservation01;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
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.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import com.example.patrice.rerservation01.vocale.reconnaissance_vocale01; // ????

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


// https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/   code source +++++

public class gestion_DB02 extends AppCompatActivity  implements View.OnClickListener
{
    Button btn_acquisition_barcode;
    Button btn_acquisition_photo;
    Button btn_saisir_name;
    Button btn_update;

    Button btn_enregistre;

    Button btn_association;
    TextView tv_nom_jeu;
    TextView tv_ean_barcode;
    TextView tv_titre_image;
    ImageView simpleImageView;

    int request_saisir_nom = 125;
    int request_capture_image = 150;

    store_statut id_class;

    private Handler handler = new Handler();

    public String SERVER = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/save_image.php",  timestamp;

    private static final String TAG = "<TAG>";

    private String retour = null;

    /***/
    JSONParser jsonParser = new JSONParser();

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

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

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


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

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.gestion_db_layout);

        setContentView(R.layout.test);

        getSupportActionBar().setTitle("Gestion de la DB");
        //getSupportActionBar().setLogo(R.drawable.listing_jeux);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        btn_acquisition_barcode = (Button) findViewById(R.id.btn_acquisition_barcode);
        btn_acquisition_barcode.setOnClickListener(this);

        btn_acquisition_photo = (Button) findViewById(R.id.btn_acquisition_photo);
        btn_acquisition_photo.setOnClickListener(this);

        btn_saisir_name = (Button) findViewById(R.id.btn_saisir_name);
        btn_saisir_name.setOnClickListener(this);

        btn_enregistre = (Button) findViewById(R.id.btn_enregistre);
        btn_enregistre.setOnClickListener(this);

        btn_update = (Button) findViewById(R.id.btn_update);
        btn_update.setOnClickListener(this);

        btn_association = (Button) findViewById(R.id.btn_association);
        btn_association.setOnClickListener(this);

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

        tv_titre_image = (TextView) findViewById(R.id.tv_titre_image);
        tv_nom_jeu = (TextView) findViewById(R.id.tv_nom_jeu);
        tv_ean_barcode = (TextView) findViewById(R.id.tv_ean_barcode);

        btn_acquisition_barcode.setEnabled(true);
        btn_acquisition_photo.setEnabled(false);
        btn_saisir_name.setEnabled(false);
        //btn_enregistre.setEnabled(false);
        btn_association.setEnabled(false);

        id_class = new store_statut();

    }

    @Override
    public void onClick(View V)
    {
        int id = V.getId();
        Intent i;

        switch(id)
        {
            case R.id.btn_acquisition_barcode:
                Toast.makeText(this, "Barcode... ", Toast.LENGTH_LONG).show();
                IntentIntegrator integrator = new IntentIntegrator(gestion_DB02.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.initiateScan();
                break;

            case R.id.btn_acquisition_photo:
                Toast.makeText(this, "Photo oh oh... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), camera_capture_image.class);
                String field_code = id_class.getCode();
                i.putExtra("code", field_code);
                startActivityForResult(i, request_capture_image );
                break;

            case R.id.btn_saisir_name:
                Toast.makeText(this, "Reconnaissance... ", Toast.LENGTH_LONG).show();
                i = new Intent(getApplicationContext(), reconnaissance_vocale01.class);
                startActivity(i);
                break;

            case R.id.btn_enregistre:
                Toast.makeText(this, "Enregistre... ", Toast.LENGTH_LONG).show();

               // OK
                //String fichier_image =   field_code = id_class.getCode();
                String fichier_image = "kate.jpeg";
                startUpload(fichier_image);
                //


                try
                {
                    retour = new nouveau_jeu().execute("titi", fichier_image ,"plouf").get();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                catch (ExecutionException e)
                {
                    e.printStackTrace();
                }

                if (retour.equals("OK"))
                {
                    Toast.makeText(gestion_DB02.this, "Ajout réussi. ", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(gestion_DB02.this, "Erreur pendant l'enregistrement !.", Toast.LENGTH_LONG).show();
                }

                // a la place , pour implémenter l'ajout dans la DB mysql

//                Bitmap image = ((BitmapDrawable) simpleImageView.getDrawable()).getBitmap();

//                Long tsLong = System.currentTimeMillis() / 1000;
//                timestamp = tsLong.toString();

//                new Upload(image,"IMG_DEBUG_aqw_"+timestamp).execute();

                //  upload_file item = new upload_file();
                //  item.upload_image();


                break;

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

            case R.id.btn_update:
                Toast.makeText(this, "Update... ", Toast.LENGTH_LONG).show();

                try
                {
                    //retour = new update_jeu().execute("13", "un", "deux","trois").get();
                    retour = new supprime_jeu().execute("10").get();

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

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

                break;

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

            case R.id.btn_association:
                Toast.makeText(this, "Association... ", Toast.LENGTH_LONG).show();
                //i = new Intent(getApplicationContext(), association.class);
                //i = new Intent(getApplicationContext(), work01.class);
                //i = new Intent(getApplicationContext(), wifi.class);
                i = new Intent(getApplicationContext(), load_imageview.class);
                startActivity(i);
                //startActivityForResult(i, request_capture_image );
                break;
        }
    }


    @Override
    protected void onResume()
    {
        super.onResume();

        String field_code = id_class.getCode();
        String field_filename = id_class.getFilename();

        if(!field_code.equals(""))
        {
            tv_ean_barcode.setText( field_code );
        }

        if(!field_filename.equals(""))
        {
            Bitmap bitmap = BitmapFactory.decodeFile( field_filename); // Environment.getExternalStorageDirectory().getPath() + field_filename );
            simpleImageView.setImageBitmap(bitmap);
        }
    }


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

        if(requestCode == request_saisir_nom)
        {
            String nom_jeu = data.getStringExtra("TAG_NOM_JEU");
            String position = data.getStringExtra("TAG_position");
            tv_nom_jeu.setText(nom_jeu);
        }

        if(requestCode == request_capture_image)
        {
            String filename =data.getStringExtra("TAG_FILENAME");
            if(filename.equals(""))
            {
                Toast.makeText(this, "Vide", Toast.LENGTH_LONG).show();
            }
            else
            {
                String path = Environment.getExternalStorageDirectory().getPath() + filename;
                id_class.setFilename(path);
                btn_enregistre.setEnabled(true);
            }
        }

        else
        {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

            if(result != null)
            {
                if (result.getContents() == null)
                {
                    Toast.makeText(this, "Pas de scan !.", Toast.LENGTH_LONG).show();
                }

                else
                {
                    String val = result.getContents();
                    id_class.setCode(val);
                    btn_acquisition_photo.setEnabled(true);
                }
            }

            else
            {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

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

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


    //Upload
    public void startUpload(final String fichier_image)
    {

        String file = Environment.getExternalStorageDirectory() + "/" + fichier_image ; //+ ".jpeg"; // avant jpeg
        //String UrlServer = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/upload_multiple.php";
        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, Void>
    {

        String resServer;

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

        @Override
        protected Void 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 null;
        }

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

    }

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

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

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

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

        if(strStatusID.equals("0"))
        {
            // FAIL
            Toast.makeText(this, "Transfert non réaliser !. ", Toast.LENGTH_LONG).show();
        }
        else
        {
            // OK
            Toast.makeText(this, "Upload réussi :) ", Toast.LENGTH_LONG).show();
        }

    }

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

    private String hashMapToUrl(HashMap<String, String> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for(Map.Entry<String, String> entry : params.entrySet())
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

    private class Upload extends AsyncTask<Void,Void,String>
    {
        private Bitmap image;
        private String name;

        // constructor
        public Upload(Bitmap image,String name)
        {
            this.image = image;
            this.name = name;
        }

        @Override
        protected String doInBackground(Void... params)
        {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //compress the image to jpg format
            image.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
            /*
            * encode image to base64 so that it can be picked by saveImage.php file
            * */
            String encodeImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

            //generate hashMap to store encodedImage and the name
            HashMap<String,String> detail = new HashMap<>();
            detail.put("name", name);
            detail.put("image", encodeImage);

            try
            {
                //convert this HashMap to encodedUrl to send to php file
                String dataToSend = hashMapToUrl(detail);
                //make a Http request and send data to saveImage.php file
                String response = request.post(SERVER,dataToSend);

                //return the response
                return response;

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Log.e(TAG,"ERROR  "+e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s)
        {
            //show image uploaded
            Toast.makeText(getApplicationContext(),"Image Uploaded",Toast.LENGTH_SHORT).show();
        }
    }

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

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

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


        protected String doInBackground(String... args)
        {
            //String nom = "gloup";
            //String image = "blase.jpeg";
            //String description = "que dal ...";

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

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("nom", nom));
            params.add(new BasicNameValuePair("image", image));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_add_jeu, "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            String reponse = null;

            // check for 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;
        }

    }

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


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

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

        protected String doInBackground(String... args)
        {
            String id = args[0];
            String nom = args[1];
            String image = args[2];
            String description = args[3];

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

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

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

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

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

        protected String doInBackground(String... args)
        {

            int success;
            String id = args[0];
            String reponse = null;

            try
            {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", id));
                JSONObject json = jsonParser.makeHttpRequest(url_supprime_jeu, "POST", params);

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

                // json success tag
                success = json.getInt(TAG_SUCCESS);

                if (success == 1)
                {
                    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;
        }

        protected void onPostExecute(String file_url)
        {
        }

    }

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

}

class store_statut
{
    private String code_barre = "";
    private String filename = "";

    public void setCode(String code_barre)
    {
        this.code_barre = code_barre;
    }

    public String getCode()
    {
        return code_barre;
    }

    public void setFilename(String filename)
    {
        this.filename = filename;
    }

    public String getFilename()
    {
        return filename;
    }


}


class request
{

    private static final String TAG = request.class.getSimpleName();

    public static String post(String serverUrl,String dataToSend)
    {
        try
        {
            URL url = new URL(serverUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            //set timeout of 30 seconds
            con.setConnectTimeout(1000 * 30);
            con.setReadTimeout(1000 * 30);
            //method
            con.setRequestMethod("POST");
            con.setDoOutput(true);

            OutputStream os = con.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));

            //make request
            writer.write(dataToSend);
            writer.flush();
            writer.close();
            os.close();

            //get the response
            int responseCode = con.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK)
            {
                //read the response
                StringBuilder sb = new StringBuilder();

                BufferedReader reader = new BufferedReader( new InputStreamReader(con.getInputStream() ) );
                String line;

                //loop through the response from the server
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line).append("\n");
                }

                //return the response
                return sb.toString();
            }
            else
            {
                Log.e(TAG,"ERROR - Invalid response code from server "+ responseCode);
                return null;
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
            Log.e(TAG,"ERROR "+e);
            return null;
        }
    }
}
