package com.example.patrice.notification_message;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

// https://www.simplifiedcoding.net/firebase-cloud-messaging-android/  php mysql
// https://www.androidhive.info/2016/10/android-push-notifications-using-firebase-cloud-messaging-fcm-php/8/
// https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
// http://www.androiddeft.com/2017/11/18/push-notification-android-firebase-php/   code super
// http://demo.androiddeft.com/firebase/notifications/

/////////////////////////////// https://www.demonuts.com/Demonuts/JsonTest/Tennis/sendMultipleFCM.php
////////////////////////////////https://demonuts.com/firebase-push-notification-multiple/

public class Main02 extends AppCompatActivity //implements View.OnClickListener
{
//    Button refresh_Button;
    Button buttonDisplayToken;
    TextView textViewToken;
    TextView champ_connexion;
    TextView tv_utilisateur;
    TextView tv_lock_user;
    ToggleButton toggleButton;

    JSONParser jParser = new JSONParser();

    private static String url_add_token_db = "http://analog-design.net/WORKAREA/WEBSITE/douche/reception.php";
    private static String url_libre_push_notification = "http://analog-design.net/WORKAREA/WEBSITE/douche/libre_push_notification.php";
    private static String url_busy_statut_notification = "http://analog-design.net/WORKAREA/WEBSITE/douche/busy_push_notification.php"; //    auto_push_statut_notification"; //   background_notification.php";

    public static final String key_nom_utilisateur = "nom_utilisateur";
    public static final String key_statut = "key_statut";

    String nom_uilisateur = null;
    String statut = "";
    String lock_user = "";

    private Handler handler = new Handler();

    private SharedPreferences.Editor mEditor;

    SharedPreferences sharedpreferences;

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

        getSupportActionBar().setTitle("  Busy ? ");
        getSupportActionBar().setLogo(R.drawable.shower);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        champ_connexion = (TextView) findViewById(R.id.champ_connexion);
        tv_lock_user = (TextView) findViewById(R.id.tv_lock_user);
        tv_utilisateur = (TextView) findViewById(R.id.tv_utilisateur);
        //refresh_Button = (Button) findViewById(R.id.refresh_Button);
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

        // affiche le nom de l'utilisateur
        nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);
        tv_utilisateur.setText(nom_uilisateur + " connected");

        if (!isNetworkAvailable())
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Réseau Internet non disponible ! \n \n Veuillez réessayer plus tard.")
                    .setIcon(R.drawable.network)
                    .setTitle("Connexion ?.")
                    .setCancelable(false)
                    .setPositiveButton("Quitter", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int id)
                        {
                            System.exit(0);
                        }
                    });

            AlertDialog alert = builder.create();
            alert.show();
        }

        if (isConnected())
        {
            champ_connexion.setBackgroundColor(0xFF00CC00);
            champ_connexion.setText("Connexion réseau");
            new HttpAsyncTask_load_douche().execute("http://analog-design.net/WORKAREA/WEBSITE/douche/lire_status_douche.php");
        }
        else
        {
            champ_connexion.setText("Probléme avec le réseau");
            champ_connexion.setBackgroundColor(Color.RED);
        }

        lire_preferences();
/*
        refresh_Button.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {

                //String contenu = tv_lock_user.getText().toString();

                new HttpAsyncTask_load_douche().execute("http://analog-design.net/WORKAREA/WEBSITE/douche/lire_status_douche.php");
            }
        });
*/
        // Set a checked change listener for toggle button
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {

                if(isChecked)
                {
                    new asyncTask_mise_a_jour_statut().execute("libre");
//                    refresh_Button.setEnabled(true);
                    new requete_notification().execute(nom_uilisateur);
                    lire_preferences();
                    Toast.makeText(getApplicationContext(), "libre", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    new asyncTask_mise_a_jour_statut().execute("busy");
//                    refresh_Button.setEnabled(false);
                    new requete_background().execute(nom_uilisateur);
                    lire_preferences();
                    Toast.makeText(getApplicationContext(), "Busy", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Toast.makeText(getApplicationContext(), "Debug on going + send + 7 juillet", Toast.LENGTH_LONG).show();


        // lance la tâche qui se répéte toute les x secondes
      //  handler.post(timedTask);
    }


    private Runnable timedTask = new Runnable()
    {
        @Override
        public void run()
        {
            //Toast.makeText(getApplicationContext(), "check", Toast.LENGTH_SHORT).show();

            // check if key_statut existe

            // si oui et que statut = "busy"

            // on met à jour les bouton  

            // affiche le nom de l'utilisateur
            //nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);

            SharedPreferences spref = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);

            if (spref.contains("key_statut"))
            {
                String value = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_statut, null);
                if(value.equals("busy"))
                {
                    //Toast.makeText(getApplicationContext(), "--- BACKGROUND ---", Toast.LENGTH_LONG).show();
                    // pour mettre à jour l'état du jeton
                    toggleButton.setText("Busy");
                    toggleButton.setEnabled(false);
                }
                if(value.equals("libre"))
                {
                    //Toast.makeText(getApplicationContext(), "--- BACKGROUND ---", Toast.LENGTH_LONG).show();
                    // pour mettre à jour l'état du jeton
                    toggleButton.setText("Libre");
                    toggleButton.setEnabled(true);
                }
            }

            handler.postDelayed(timedTask, 1000); // 1 seconde
        }};

    // ne pas oublier de tuer la tache pour sauvegarder la batterie
    // to remove handler.removeCallbacks(timedTask);


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


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

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

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

            JSONObject json = jParser.makeHttpRequest(url_libre_push_notification, "POST", 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();
            }
*/

            return(null);
        }

        protected void onPostExecute(String s)
        {


        }
    }


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

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

        }

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

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

            JSONObject json = jParser.makeHttpRequest(url_busy_statut_notification, "POST", params);

            return(null);
        }

        protected void onPostExecute(String s)
        {

        }
    }

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

    public void lire_preferences()
    {
        SharedPreferences spref = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);

        if (spref.contains("key_statut"))
        {
            String value = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_statut, null);
            Toast.makeText(getApplicationContext(), "------>" + value, Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(), "??????????", Toast.LENGTH_SHORT).show();
        }
    }

    /***********************************************************************/
    private boolean isNetworkAvailable() {
        // Using ConnectivityManager to check for Network Connection
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

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

    public boolean isConnected()
    {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

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

    private class HttpAsyncTask_load_douche extends AsyncTask<String, String, String>
    {
        @Override
        protected String doInBackground(String... urls) {
            String url = urls[0];
            InputStream inputStream = null;
            String result = "";

            try {
                // creation du HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                // faire une requete de type GET sur l'url suivante
                HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
                // reception de la reponse
                inputStream = httpResponse.getEntity().getContent();
                // convertir inputstream en string
                if (inputStream != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String line = "";

                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }

                    inputStream.close();
                } else
                    result = "Probleme mon gars!";
            } catch (Exception e) {
                Log.d("InputStream", e.getLocalizedMessage());
            }

            return result;

        }

        @Override
        protected void onPostExecute(String result)
        {
            if (result.contains("-"))
            {
                String[] parts = result.split("-");
                statut = parts[0];
                lock_user = parts[1];
                //toggleButton.setChecked(false);
                toggleButton.setText("Busy");
                tv_lock_user.setText("Busy : " + lock_user);

                if (!lock_user.equals(nom_uilisateur)) // seul le lock_user peut relacher l'état occuper vers libre
                {
                    toggleButton.setEnabled(false);
                }
                else
                {
                    toggleButton.setEnabled(true);
                }

            }

            else
            {
                // toggleButton.setChecked(true);
                toggleButton.setText("Libre");
                tv_lock_user.setText("");
                toggleButton.setEnabled(true);
            }
        }
    }


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

    private class asyncTask_mise_a_jour_statut extends AsyncTask<String, String, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            postData(params[0]);
            return (params[0]);
        }

        public void postData(String etat)
        {
            // nouveau client Http
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.analog-design.net/WORKAREA/WEBSITE/douche/mise_a_jour_douche.php");

            String sauvegarde = null;

            tv_lock_user = (TextView) findViewById(R.id.tv_lock_user);

            try
            {
                if (etat.equals("busy"))
                {
                    sauvegarde = etat + "-" + nom_uilisateur; // + "-" + getCurrentTime();
                }
                else
                {
                    sauvegarde = etat;
                }

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("HttpData", sauvegarde));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute une requete HTTP Post
                HttpResponse response = httpclient.execute(httppost);
            }

            catch (ClientProtocolException e)
            {
            }

            catch (IOException e)
            {
            }


        }

        protected void onPostExecute(String result)
        {
            if (result.equals("busy")) {
                tv_lock_user.setText("Busy : " + nom_uilisateur);
            } else {
                tv_lock_user.setText("");
            }
        }

    }

    /************************************************************************/
/*
    public class update_database extends AsyncTask<String, Void, String> {

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

        @Override
        protected String doInBackground(String... args)
        {
            String token = args[0];

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

            JSONObject json = jParser.makeHttpRequest(url_add_token_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(), "Token ajouter avec succés", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Erreur de traitement : Sauvegarde impossible !", Toast.LENGTH_LONG).show();
            }
        }
    }
*/

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /************************************************************************/
    // menu dans la l'action bar
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent i;

        switch (item.getItemId()) {
            case R.id.item1:
                i = new Intent(getApplicationContext(), aide.class);
                startActivity(i);
                break;

            case R.id.item2:
                i = new Intent(getApplicationContext(), token.class);
                startActivity(i);
                break;

            case R.id.item3:
                about();
                break;

            case android.R.id.home:
                quitter_confirmation();
                return true;
        }


        return super.onOptionsItemSelected(item);
    }

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

    public void about()
    {
        final Dialog dialog = new Dialog(Main02.this);

        dialog.setContentView(R.layout.about_layout);
        dialog.setTitle("About:");
        dialog.show();

        Button dialogCloseButton = (Button) dialog.findViewById(R.id.close_button);

        dialogCloseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }

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

    public void quitter_confirmation()
    {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        alertDialogBuilder.setTitle("Confirmation");

        alertDialogBuilder
                .setMessage("Quitter l'appli ?.")
                .setCancelable(false)
                .setPositiveButton("Oui", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Toast.makeText(Main02.this, "A bientôt ...", Toast.LENGTH_SHORT).show();
                        handler.removeCallbacks(timedTask);

                        /// supprimer la clé et sa valeur
                        sharedpreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedpreferences.edit();
                        editor.putString(key_statut, "*******");
                        //editor.remove(key_statut);
                        editor.apply();





                        Main02.this.finishAffinity();
                        System.exit(0);
                    }
                })

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

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

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

    public void onBackPressed()
    {
        quitter_confirmation();
    }

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


}