package com.example.patrice.reservation02.service_alarm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.example.patrice.reservation02.JSONParser;
import com.example.patrice.reservation02.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;


import static android.content.Context.MODE_PRIVATE;


public class boot_alarm_receiver extends BroadcastReceiver
{

    JSONParser jsonParser = new JSONParser();

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_JEU = "jeu_emprunter";
    private static final String TAG_NOM = "jeu";

    private static String requete_service_restitution = "http://analog-design.net/WORKAREA/WEBSITE/reservation/requete_service_restitution.php";

    JSONArray datas = null;

    ArrayList<String> liste_jeu_notification = new ArrayList<String>();
    String concate;

    Context ctx = null;

    public static final String key_nom_utilisateur = "nom_utilisateur";

    @Override
    public void onReceive(Context context, Intent intent)
    {

        ctx = context;

        String nom_uilisateur = context.getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE).getString(key_nom_utilisateur,null);
        //String nom_uilisateur = context.getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);
        async_requete_http updateTask = new async_requete_http();
        updateTask.execute(nom_uilisateur);

    }

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

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

        }

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

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

            JSONObject json = jsonParser.makeHttpRequest(requete_service_restitution, "GET", params);
            Log.v("***** JSON BOOT: ", client + " " + json.toString());

            try
            {
                int success = json.getInt(TAG_SUCCESS);

                liste_jeu_notification.clear();

                //
                if (success == 0)
                {
                    datas = json.getJSONArray(TAG_JEU);

                    for (int i = 0; i < datas.length(); i++)
                    {
                        JSONObject c = datas.getJSONObject(i);
                        String jeu = c.getString(TAG_NOM);
                        liste_jeu_notification.add(jeu);
                    }

                }

                if (success == 1)
                {
                    // tout va bien
                }

            }

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

            return("none");
        }

        protected void onPostExecute(String s)
        {

            boolean check = liste_jeu_notification.isEmpty();
            int nb_element = liste_jeu_notification.size();

            if( nb_element != 0 )
            {
                concate = android.text.TextUtils.join(", ", liste_jeu_notification);
                String str = "Vous devez rapporter les jeux suivants:  \n " + concate;
                notification(str);
            }

        }
    }


    public void notification(String msg)
    {
        int num = 0;

        NotificationManager notificationManagerCompat = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx)
                //.setTicker("Retour jeu ludothéque !")
                .setContentTitle("Ludo notification...")
                .setSmallIcon(R.drawable.notification) // worldwide

                //.setLargeIcon()


                // .setContentText("message")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))

                .setColor(ContextCompat.getColor(ctx, android.R.color.black))
                //.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setSound(alarmSound)

                .setContentIntent(PendingIntent.getActivity(ctx, 0, new Intent(ctx, cancel_notification.class), PendingIntent.FLAG_UPDATE_CURRENT))

                .setAutoCancel(true);

        builder.build().flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;

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

        Log.v("*********", "NOTIFICATION BOOT");

    }

}