package com.example.patrice.appli_04;

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

public class boot_alarm_receiver extends BroadcastReceiver
{

    String load_nom = null;          // 0
    String load_barcode = null;      // 1
    String load_description = null;  // 2
    String load_image = null;        // 3

    boolean flag_checkin = false;


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


    Context ctx = null;


    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 url_requete_infos_jeu = "http://analog-design.net/WORKAREA/WEBSITE/reservation/requete_infos_jeu.php";
    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;

    String retour = null;


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

        ctx = context;

        //requete updateTask = new requete();
        //updateTask.execute("3");

        async_requete_http updateTask = new async_requete_http();
        updateTask.execute("patoche");

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

        //Intent i = new Intent(context, alert_dialog.class);
        //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //context.startActivity(i);
/*
        int num = 0;

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

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

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                //.setTicker("Retour jeu ludothéque !")
                .setContentTitle("BOOT launcher ...")
                .setSmallIcon(R.drawable.worldwide)
                .setContentText("message")
                .setColor(ContextCompat.getColor(context, android.R.color.black))
                //.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setSound(alarmSound)

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

                .setAutoCancel(true);

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

        notificationManagerCompat.notify(num, builder.build());
*/

    }

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

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

        }

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

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

            JSONObject json = jsonParser.makeHttpRequest(url_requete_infos_jeu, "GET", params);
            Log.v("Affiche format JSON: ", json.toString());

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

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

                    }

                }

                if (success == 1)
                {

                    // tout va bien
                    /*
                    JSONArray productObj = json.getJSONArray("jeu");
                    // le premier element, car il y en a un seul !
                    JSONObject product = productObj.getJSONObject(0);

                    load_nom = product.getString("nom");
                    load_description = "blabla..."; //product.getString("description");
                    load_barcode = product.getString("barcode");
                    load_image = product.getString("image");

                    String message = load_nom + "&" + load_description + "&" + load_barcode + "&" + load_image;

                    flag_checkin = true;

                    Log.v(" HTTP ******* ", message);
                    */
                }

                else
                {
                    // erreur non prévu
                }
            }

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

            return("toto");
        }

        protected void onPostExecute(String s)
        {

            notification(s);

        }
    }

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

    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("********* Affiche format JSON: ", 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("BOOT launcher ...")
                .setSmallIcon(R.drawable.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(num, builder.build());

    }

}