package com.example.patrice.appli_04;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
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 appli_alarm_service extends Service
{
    private NotificationManager mNM;

    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_service_restitution.php";


    String message;


    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 onCreate()
    {
        //Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
        Log.v("*********", "PLOUF");
        //  mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //   showNotification();

    }

    @Override
    public IBinder onBind(Intent intent)
    {
        //Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
        return null;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
        mNM.cancel(0);

    }
    @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        //Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();

        Log.v("*********", "BINGO");
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        action();

    }

    @Override
    public boolean onUnbind(Intent intent)
    {
        //Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
        return super.onUnbind(intent);
    }

    private void action()
    {

       // requete updateTask = new requete();

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

    }

    private void showNotification(String msg)
    {

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        builder.setSmallIcon(R.drawable.android);
        builder.setContentTitle("Firsr run");
        //builder.setContentText(msg);

        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg));

        builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, cancel_notification.class), PendingIntent.FLAG_UPDATE_CURRENT));

        builder.setAutoCancel(true);

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

        builder.setVibrate(new long[] { 0, 200, 100, 200 });
        final Notification notification = builder.build();

        mNM.notify(0, notification);

        Log.v("*********", "NOTIFICATION first run ..");

        //NOTIFICATION += 1;
    }

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

    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 == 1)
                {
                    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");

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

                    flag_checkin = true;

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

                }

                else
                {
                    // erreur
                }
            }

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

            return(message);
        }

        protected void onPostExecute(String s)
        {
            showNotification(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;
                showNotification(str);
            }

        }
    }
}