package com.example.patrice.occupation02;

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.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Settings;
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.ImageButton;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class appli05 extends AppCompatActivity
{
    Timer timer;
    boolean occupation = false;
    private boolean position = true;
    private String message = "";
    TextView champ_connexion;
    TextView tv_utilisateur;
    TextView tv_lock_user;
    TextView tv_time_lapse;
//    ImageButton imageButton;

    String pipo;

    SharedPreferences.Editor editor;

    public static final String key_nom_utilisateur = "nom_utilisateur";

    String nom_uilisateur = null;

    int sec = 0, min = 0, hr = 0;

    MediaPlayer Player;

    private String previous = "";

    String statut = "";
    String lock_user = "";
    String temps = "";

    private MediaPlayer mediaPlayer;

    private ToggleButton toggleButton;

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

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

        //imageButton = (ImageButton) findViewById(R.id.img_btn);
        champ_connexion = (TextView) findViewById(R.id.champ_connexion);

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

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);

        SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("PREFERENCE", 0); // 0 - for private mode
        Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);
        //   RESET pour le debug
        //   getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", true).commit();

        // premier run on doit valider l'enregristrement du client
        if (isFirstRun) {
            startActivity(new Intent(appli05.this, creation_compte.class));
        }

        // 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()) // pour le debug on supprime la négation !
        {
            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) {
                            // Restart the Activity
                            //Intent intent = getIntent();
                            System.exit(0);
                            //finish();
                            //startActivity(intent);
                        }
                    });

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

        // Set a checked change listener for toggle button
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {

                if(isChecked)
                {

                    //if (!lock_user.equals(nom_uilisateur)) // seul le lock_user peut relacher l'état occuper vers libre
                    //{
                    //    Toast.makeText(getApplicationContext(), "Attendre que l'utilisateur libére la douche", Toast.LENGTH_SHORT).show();
                    //}

                        //Toast.makeText(getApplicationContext(), "Toggle is on", Toast.LENGTH_SHORT).show();
                        new asyncTask_mise_a_jour_statut().execute("libre");
                }
                else
                {
                    //Toast.makeText(getApplicationContext(), "Toggle is off", Toast.LENGTH_SHORT).show();
                    new asyncTask_mise_a_jour_statut().execute("busy");
                }
            }
        });


        timer = new Timer();

        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        new HttpAsyncTask_load_douche().execute("http://analog-design.net/WORKAREA/WEBSITE/douche/lire_status_douche.php");

                        sec++;
                        if(sec==59)
                        {
                            min++;
                            sec=0;
                        }
                        if(min==59)
                        {
                            min=0;
                            hr++;
                        }
                        if(hr==23)
                        {
                            hr=00;
                        }

                        if(min == 40)
                        {
                            timer.cancel();
                            timer = null;
                            appli05.this.finishAffinity();
                            System.exit(0);

                        }

                    }
                });

            }
        }, 0, 3000); // attendre 500ms

    }

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

    public String getCurrentTime()    //View view)
    {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
        String strDate = mdformat.format(calendar.getTime());
        return (strDate);
    }

    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("");
            }
        }

    }

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

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

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

    @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:
                about();
                break;

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


        return super.onOptionsItemSelected(item);
    }

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

    public void about() {
        final Dialog dialog = new Dialog(appli05.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(appli05.this, "A bientôt ...", Toast.LENGTH_SHORT).show();

                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                        }

                        appli05.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() {
        //super.onBackPressed();
        //finish();
        //System.exit(0);
        //moveTaskToBack(true);

        quitter_confirmation();
    }
}
