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.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
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 MainActivity 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;

    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 = "";

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

        getSupportActionBar().setTitle("  Douche  ");
        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);

        Ringtone defaultRingtone = RingtoneManager.getRingtone(getApplicationContext(),
                Settings.System.DEFAULT_RINGTONE_URI);
        //fetch current Ringtone
        Uri currentRintoneUri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE);
        Ringtone currentRingtone = RingtoneManager.getRingtone(getApplicationContext(), currentRintoneUri);


       // currentRingtone.play();
       // Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
       // Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
       // ringtone.play();

        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(MainActivity.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_statut_douche().execute("http://analog-design.net/WORKAREA/WEBSITE/douche/lire_status_douche.php");
        }
        else
        {
            champ_connexion.setText("Probléme avec le réseau");
            // on cache le bouton
            imageButton.setVisibility(View.GONE);
            champ_connexion.setBackgroundColor(Color.RED);
            //alarm.setVisibility(View.VISIBLE);
        }

        imageButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {

                    if (!position) // occupation
                    {
                         //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_LONG).show();
                         //}

                             position = true;
                             new asyncTask_mise_a_jour_statut().execute("libre");
                             imageButton.setImageResource(R.drawable.check);


                    }
                    else
                    {
                        position = false;
                        new asyncTask_mise_a_jour_statut().execute("occuper");
                        imageButton.setImageResource(R.drawable.error);
                    }

            }

        });

        timer = new Timer();

        timer.schedule(new TimerTask()
        {
            int count=0;

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

                        //tv_utilisateur.setText("count="+count);
                        //count++;

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

                        String time_lapse = String.valueOf(hr) + ":" + String.valueOf(min) + ":" + String.valueOf(sec);

                        Calendar c = Calendar.getInstance();
                        int hours = c.get(Calendar.HOUR_OF_DAY);
                        int minutes = c.get(Calendar.MINUTE);
                        int seconds = c.get(Calendar.SECOND);
                        String curTime = String.format("%02d  %02d  %02d", hours, minutes, seconds);

                        tv_time_lapse.setText(time_lapse); //change clock to your textview


                    }
                });

            }
        }, 0, 1000); // attendre 1s

    }

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

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

    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_statut_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)
        {
            String reponse = "";

            if(result.contains("-"))
            {
                String[] parts = result.split("-");
                statut = parts[0];
                lock_user = parts[1];
                temps = parts[2];
                tv_lock_user.setText(lock_user + " occupe la douche depuis " + temps);

                if (result.equals("libre"))
                {
                    //alarm.setText("Douche disponible");
                    position = true;
                    imageButton.setImageResource(R.drawable.check);

                    //Toast.makeText(getApplicationContext(), "Douche disponible", Toast.LENGTH_LONG).show();
                }

                // occuper
                else
                {
                    //alarm.setText("ALARME OFF");
                    position = false;
                    imageButton.setImageResource(R.drawable.error);
                    //Toast.makeText(getApplicationContext(), "Douche occupée !", Toast.LENGTH_LONG).show();

                   /* if(!lock_user.equals(nom_uilisateur))
                    {
                        imageButton.setEnabled(false);
                    }
                    else
                    {
                        imageButton.setEnabled(true);
                    }*/

                }
            }

            else
            {
                if (result.equals("libre"))
                {
                    //alarm.setText("Douche disponible");
                    position = true;
                    imageButton.setImageResource(R.drawable.check);
                    //Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                    //Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
                    //ringtone.play();
                    //Toast.makeText(getApplicationContext(), "Douche disponible", Toast.LENGTH_LONG).show();
                }

                // occuper
                else
                {
                    //alarm.setText("ALARME OFF");
                    position = false;
                    imageButton.setImageResource(R.drawable.error);
                    //Toast.makeText(getApplicationContext(), "Douche occupée !", Toast.LENGTH_LONG).show();
                }
            }

        }
    }

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

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

        protected String doInBackground(String... args)
        {
            return (null);
        }

        protected void onPostExecute(String s)
        {
            Toast.makeText(getApplicationContext(), "Timer 10s", Toast.LENGTH_SHORT).show();
        }
    }

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

    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("occuper"))
                {
                    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("occuper"))
            {
                tv_lock_user.setText(nom_uilisateur + " occupe la douche depuis" + getCurrentTime());
                position = false;
                Toast.makeText(getApplicationContext(), "Douche occupée !", Toast.LENGTH_SHORT).show();
            }
            else
            {
                tv_lock_user.setText("");
                position = true;
                Toast.makeText(getApplicationContext(), "Douche disponible", 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;
    }

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

    @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(MainActivity.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(MainActivity.this, "A bientôt ...", Toast.LENGTH_SHORT).show();

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

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

    //if(waitTimer != null)
    //{
    //    waitTimer.cancel();
    //    waitTimer = null;
    //}


}

/*
    PowerManager pm;
    PowerManager.WakeLock wl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "satish");

        wl.acquire();
        //...
        wl.release();
    }


        @Override
        protected void onPause() {
            super.onPause();
            wl.release();
        }//End of onPause

        @Override
        protected void onResume() {
            super.onResume();
            wl.acquire();
        }//End of onResume


    FULL_WAKE_LOCK – the screen is on full bright, the keyboard backlight is on, and the CPU is running
    SCREEN_BRIGHT_WAKE_LOCK – the screen is on full bright, and the CPU is running
    SCREEN_DIM_WAKE_LOCK – the screen is on, it’s able to be dimmed, and the CPU is running
    PARTIAL_WAKE_LOCK – the screen and keyboard backlight may be turned off but it keeps the CPU running. This is commonly used for Services started with intent receivers which may receive intents while the device is asleep


*/