package com.example.patrice.firebase_database;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
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 com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;

import com.google.android.gms.common.ConnectionResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

// http://www.technotalkative.com/android-how-to-display-information-with-justify-alignment/

// https://www.youtube.com/watch?v=wV3FdPNS_xk

public class Main05 extends AppCompatActivity
{
    private static final String TAG = "MainActivity";
    private FirebaseDatabase mDatabase;
    private DatabaseReference mDbRef;
    private String userId;


    TextView champ_connexion;
    TextView tv_utilisateur;
    TextView tv_lock_user;
    ToggleButton toggleButton;

    String nom_uilisateur = null;
    String statut = null;
    String utilisateur = null;

    String memoire_utilisateur = null;

    SharedPreferences sharedpreferences;

    public static final String key_inscription_nom_utilisateur = "key_inscription_nom_utilisateur";

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

        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);
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);


        //checkPlayServices();
        //isGooglePlayServicesAvailable(this);
        //checkGooglePlayServicesAvailability();

        // affiche le nom de l'utilisateur
        nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_inscription_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");
        }
        else
        {
            champ_connexion.setText("Probléme avec le réseau");
            champ_connexion.setBackgroundColor(Color.RED);
        }

        // Write a message to the database
        mDatabase = FirebaseDatabase.getInstance();
        mDbRef = mDatabase.getReference("Shower");

        //Setting firebase unique key for Hashmap list
        //String userId = mDbRef.push().getKey();

        // creating user object
        //shower user = new shower("libre", "none");
        //mDbRef.child("Datas").setValue(user);

        mDbRef.addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                shower userxx = dataSnapshot.child("Datas").getValue(shower.class);


                String s = tv_lock_user.getText().toString();
                String[] split_string = s.split(" : ");

                statut = userxx.getStatut();
                utilisateur = userxx.getUser();

                if(statut.equals("libre"))
                {
                    toggleButton.setText("Libre");
                    toggleButton.setEnabled(true);
                    tv_lock_user.setText("");

                    if(split_string.length == 2)
                    {
                        if (!split_string[1].equals(nom_uilisateur)) // different
                        {
                            addNotification();
                        }
                    }
                        //  if(nom_uilisateur different )

                }
                if(statut.equals("busy"))
                {
                    toggleButton.setText("Busy");

                    if (utilisateur.equals(nom_uilisateur))
                    {
                        toggleButton.setEnabled(true);

                        toggleButton.setChecked(false);  // pouvoir éviter la zone morte

                    }
                    else
                    {
                        toggleButton.setEnabled(false);
                    }
                        tv_lock_user.setText("Busy : " + utilisateur);
                }

                //Log.d(TAG, "User name: " + userxx.getStatut() + ", email " + userxx.getUser());
            }
            @Override
            public void onCancelled(DatabaseError error)
            {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });


        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    // libre
                    toggleButton.setEnabled(true);
                    shower user = new shower("libre", "none");
                    mDbRef.child("Datas").setValue(user);
                    tv_lock_user.setText("");
                    //if( !memoire_utilisateur.equals(nom_uilisateur) )
                    //{
                    //    addNotification();
                    //}
                }
                else
                {
                    // busy
                    shower user = new shower("busy", nom_uilisateur);
                    mDbRef.child("Datas").setValue(user);
                    tv_lock_user.setText("Busy : " + nom_uilisateur);
                    //memoire_utilisateur = nom_uilisateur;

                    if (utilisateur.equals(nom_uilisateur))
                    {
                        toggleButton.setEnabled(true);
                    }
                    else
                    {
                        toggleButton.setEnabled(false);
                    }

                    //addNotification();

                }
            }
        });


    }

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

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

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

    public boolean isGooglePlayServicesAvailable(Activity activity)
    {
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
        if(status != ConnectionResult.SUCCESS) {
            if(googleApiAvailability.isUserResolvableError(status)) {
                googleApiAvailability.getErrorDialog(activity, status, 2404).show();
            }
            return false;
        }
        return true;
    }

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

    private boolean checkPlayServices()
    {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS)
        {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
            {
                Toast.makeText(getApplicationContext(), "This device is supported. Please download google play services", Toast.LENGTH_LONG)
                        .show();
            } else {
                Toast.makeText(getApplicationContext(), "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

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

    public void checkGooglePlayServicesAvailability() {
        int statusCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (statusCode == ConnectionResult.SUCCESS) {
            Log.d("Google Play services ?", "" + statusCode);
        } else {

            GooglePlayServicesUtil.getErrorDialog(statusCode, this, 0).show();
        }
    }

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

    private void addNotification()
    {
       /* NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.shower)
                        .setContentTitle("Notifications Example")
                        .setContentText("This is a test notification");

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        // Add as notification
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());*/

        // Creating Intent.
        Intent intent = new Intent(this, MainActivity.class);

        // Device vibrate pattern.
        long[] pattern = {500,500,500,500,500};

        // Adding FLAG_ACTIVITY_CLEAR_TOP to intent.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Creating Pending Intent object.
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 , intent, PendingIntent.FLAG_UPDATE_CURRENT);


        // Creating URI to access the default Notification Ringtone.
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // Converting drawable icon to bitmap for default notification ICON.
        Bitmap DefaultIconBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        // Building Notfication.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)

                // Adding Default Icon to Notification bar.

                .setSmallIcon(R.drawable.shower)

                //.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

                // Setting up Title.
                .setContentTitle("Douche libre")

                // Setting the default msg coming from server into Notification.
                //.setContentText("messageBody")

                .setAutoCancel(true)

                .setVibrate(pattern)

                .setSound(defaultSoundUri)

                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, builder.build());

    }


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

    @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:
                quitter_confirmation();
                return true;
        }


        return super.onOptionsItemSelected(item);
    }

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

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

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

}

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

// Now we set the vibrate member variable of our Notification
// After a 100ms delay, vibrate for 200ms then pause for another
//100ms and then vibrate for 500ms
//n.vibrate = new long[]{100, 200, 100, 500};

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

/*
    // This code snippet will cause the phone to vibrate "SOS" in Morse Code
// In Morse Code, "s" = "dot-dot-dot", "o" = "dash-dash-dash"
// There are pauses to separate dots/dashes, letters, and words
// The following numbers represent millisecond lengths
    int dot = 200;      // Length of a Morse Code "dot" in milliseconds
    int dash = 500;     // Length of a Morse Code "dash" in milliseconds
    int short_gap = 200;    // Length of Gap Between dots/dashes
    int medium_gap = 500;   // Length of Gap Between Letters
    int long_gap = 1000;    // Length of Gap Between Words
    long[] pattern = {
            0,  // Start immediately
            dot, short_gap, dot, short_gap, dot,    // s
            medium_gap,
            dash, short_gap, dash, short_gap, dash, // o
            medium_gap,
            dot, short_gap, dot, short_gap, dot,    // s
            long_gap
    };
*/

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