package com.example.patrice.reservation02;

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 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.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;


public class ajouter_jeu extends AppCompatActivity
{

    JSONParser jParser = new JSONParser();
    private static final String TAG_SUCCESS = "success";

    EditText et_nom, et_description;
    Button btn_scanner, btn_capture_image, btn_enregistre;


    int request_capture_image = 150;

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

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

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

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


    String jeu_nom;

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

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

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

        btn_enregistre.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                    String jeu_nom = et_nom.getText().toString();
                    new requete_infos_jeu().execute(jeu_nom);
            }
        });
    }

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

    // 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 requete_infos_jeu extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

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

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

            JSONObject json = jParser.makeHttpRequest(url_request_data_existe, "GET", params);
            Log.d("Affiche format JSON: ", json.toString());

            String reponse = null;
            String msg = null;

            try
            {
                msg =  json.getString("message");

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

                else
                {
                    reponse = "vide";
                }
            }

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


            String concate = reponse + "&" + nom;

            return concate;

        }

        protected void onPostExecute(String s)
        {
            String[] parts = s.split("&");

            if(parts[0].equals("existe"))
            {
                Toast.makeText(getApplicationContext(), "Impossible le jeu existe dans la database ! ", Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
                //new ajouter_jeu_db().execute(parts[1]);
                new update_database().execute(parts[1]);
            }

        }
    }

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

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

        }

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

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("nom", nom));
            JSONObject json = jParser.makeHttpRequest(url,  "POST", params);

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

            String res = "";

            try
            {
                //String success = json.getString(TAG_SUCCESS);
                String success = json.getString("success");

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

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

            return(res);
        }

        protected void onPostExecute(String res)
        {

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

        }

    }

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


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

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            String url_admin_update_jeu_db = "http://analog-design.net/WORKAREA/WEBSITE/reservation/debug_add.php";

            params.add(new BasicNameValuePair("nom", nom));
            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(), "Jeu insérer dans la database.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Erreur de traitement : Sauvegarde impossible !", Toast.LENGTH_LONG).show();
            }
        }
    }

}