package com.example.patrice.rerservation01.service_alarm;

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;

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

public class appli_alarm_service extends Service
{
    private NotificationManager mNM;

    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;

    public static final String key_nom_utilisateur = "nom_utilisateur";

    boolean debug_mode = true;

    @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()
    {
        String nom_uilisateur = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getString(key_nom_utilisateur, null);

        /*if(debug_mode)
        {
            nom_uilisateur = "patoche";
        }*/

        async_requete_http updateTask = new async_requete_http();
        updateTask.execute(nom_uilisateur);
    }

    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 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("********* Retour JSON alarme service: ", 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;
                showNotification(str);
            }

        }
    }
}