package com.example.patrice.notification_message;


        import android.app.NotificationManager;
        import android.app.PendingIntent;
        import android.content.Context;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.media.RingtoneManager;
        import android.net.Uri;
        import android.os.Handler;
        import android.support.v4.app.NotificationCompat;
        import android.util.ArrayMap;
        import android.util.Log;
        import android.widget.Toast;


        import com.google.firebase.messaging.FirebaseMessagingService;
        import com.google.firebase.messaging.RemoteMessage;

        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;

        import java.util.ArrayList;
        import java.util.Arrays;
        import java.util.Iterator;
        import java.util.List;
        import java.util.Map;

        import static com.example.patrice.notification_message.R.id.tv_lock_user;


/**
 * Created by Belal on 03/11/16.
 */



public class MyFirebaseMessagingService extends FirebaseMessagingService {


    SharedPreferences sharedpreferences;
    public static final String key_statut = "key_statut";


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        //Method To Generate Notification.


      //  sendNotification( remoteMessage.getData() );

      //  String titre = remoteMessage.getData().get("title").toString();

     //   String title = remoteMessage.getNotification().getTitle();
     //   String message = remoteMessage.getNotification().getBody();



        for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            Log.v("TAG", "key, " + key + " value " + value);
        }


        Log.e("dataChat",remoteMessage.getData().toString());
        try
        {

            JSONObject json = new JSONObject(remoteMessage.getData().toString());

            Map<String, String> params = remoteMessage.getData();

           String  title = remoteMessage.getData().get("title");

            JSONObject object = new JSONObject(params);
            Log.e("JSON_OBJECT", object.toString());
        }

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

        Map data = remoteMessage.getData();
        JSONObject json = new JSONObject(data);


/*
        try{
            JSONObject jsonxx = new JSONObject(data);
            Iterator<String> iterator =  jsonxx.keys();
            while (iterator.hasNext()){
                String key =  iterator.next();

                JSONObject object = jsonxx.getJSONObject(key);
                String value1 = object.getString("title");
                String value2 = object.getString("message");
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
*/


/*

        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            System.out.println(pair.getKey() + " : " + pair.getValue());
        }
*/


/*************************  OK *******************************************/

        Iterator it = json.keys();

        String value = null;

        boolean arrFlag = false;
        while (it.hasNext()) {
            String key = (String) it.next();
            if (!arrFlag) {
                value = null;
                try {
                    value = json.getString(key);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i("Key:Value", "" + key + ":" + value);
                arrFlag = true;
            }
        }


         // nettoyage
        String replace = value.replace("{","");
        replace = replace.replace("}","");
        replace = replace.replace("\"","");
        List<String> myList = new ArrayList<String>(Arrays.asList(replace.split(",")));

        String item_title = myList.get(0);
        String[] aaa = item_title.split(":");
        String item_message = myList.get(1);
        String[] bbb = item_message.split(":");

        String tmp = aaa[1] + " " + bbb[1];

        if(aaa[1].equals("statut") && bbb[1].equals("busy") )
        {
            preferences_save("busy");
        }

        if(aaa[1].equals("statut") && bbb[1].equals("libre") )
        {
            preferences_save("libre");
            FirebaseCloudMessageFunction(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
        }
/*
        else
        {
            FirebaseCloudMessageFunction(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
        }
*/
        for (String item : aaa)
        {
            System.out.println(item);
        }

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


        String jsonstring = "data" + ":" + value;
        JSONObject resobj = null;
        try {
            resobj = new JSONObject(jsonstring);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Iterator<?> keys = resobj.keys();
        while(keys.hasNext() ) {
            String key = (String)keys.next();
            try {
                if ( resobj.get(key) instanceof JSONObject ) {
                    JSONObject xx = new JSONObject(resobj.get(key).toString());
                    Log.d("res1",xx.getString("title"));
                    Log.d("res2",xx.getString("message"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        for(Iterator<String> iter = json.keys();iter.hasNext();)
        {
            String key = iter.next();
            }



        Log.d("**** TAG ***", remoteMessage.getFrom());

        // Check if message contains a data payload.
        //if (remoteMessage.getData().size() > 0) {
        //    Log.d("**** TAG ***", "Message data payload: " + remoteMessage.getData());
        //    Map<String, String> datas = remoteMessage.getData();
        //   }

        try {





            // getting address
            Map address = ((Map)json.get("data"));

            // iterating address Map
            Iterator<Map.Entry> itr1 = address.entrySet().iterator();
            while (itr1.hasNext()) {
                Map.Entry pair = itr1.next();
                System.out.println(pair.getKey() + " : " + pair.getValue());
            }




        }

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

   //     JSONArray array = new JSONArray(json.getString("data"));



        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        Log.e("JSON_OBJECT", object.toString());


        FirebaseCloudMessageFunction(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));

/*
        if(remoteMessage.getData().get("title").equals("statut") && remoteMessage.getData().get("body").equals("busy") )
        {
            preferences_save("busy");
        }

        else
        {
            FirebaseCloudMessageFunction(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
        }
        */
       // traitement cls2 = new traitement();
       // cls2.toto();

    }


    private void sendNotification(Map<String,String> messageBody)
    {
// https://medium.com/@chahat.jain0/android-push-notifications-using-firebase-cloud-messaging-fcm-php-and-mysql-da571960aeba



   /*
        for (int i = 0; i < messageBody.size(); i++) {
            String key = messageBody.get() .keyAt(i);
            String value = messageBody.valueAt(i);
        }

        String zzz = messageBody.get("title");
        String xxx = messageBody.get("message");*/
    }

    // Function to Generate Push Notification After Receiving Response from Server.
    private void FirebaseCloudMessageFunction(String messageTitle, String messageBody) {

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

       traitement a = new traitement();
       a.toto();


       //MainActivity app = new MainActivity();
       //app.display();

//        showToast();

        writeLine("Douche disponible");
    }

    public void preferences_save(String statut)
    {
        sharedpreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(key_statut, statut);
        editor.commit();

    }

    public void showToast()
    {
        /*
        MainActivity.runOnUiThread(new Runnable() {
            public void run()
            {
                Toast.makeText(MainActivity, "toast", Toast.LENGTH_SHORT).show();
            }
        });*/

        final Context context = null;

        ((MainActivity)context).runOnUiThread(new Runnable()
        {
            public void run()
            {
                Toast.makeText(context, "toast", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void writeLine(final String message) {
        Handler h = new Handler(getApplicationContext().getMainLooper());
// Although you need to pass an appropriate context
        h.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
                //MainActivity app = new MainActivity();
                //app.display();




            }
        });
    }

/*

    private Runnable updateUI = new Runnable() {
        @Override
        public void run() {


            tv_lock_user.setText("dgsgqgd");



            handler.postDelayed(this, 1000);
        }
    };

    private void setAndUpdateUI(){
        runOnUiThread(updateUI);
    }
*/
}
