package com.example.patrice.job_scheduler_01;

import android.app.NotificationManager;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
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;


// https://github.com/AdeWijaNugraha/JobScheduler

public class MyJobService extends JobService
{

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

    JSONParser jsonParser = new JSONParser();


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

    private static final String TAG_SUCCESS = "success";



    static final String TAG = MyJobService.class.getSimpleName();

  //  private UpdateAppsAsyncTask updateTask = new UpdateAppsAsyncTask();

    requete updateTask = new requete();

    @Override
    public boolean onStartJob(JobParameters params)
    {
        // Note: this is preformed on the main thread.
        Log.d(TAG, "onStartJob id=" + params.getJobId());

        updateTask.execute("3");

        return true;
    }

    // Stopping jobs if our job requires change.

    @Override
    public boolean onStopJob(JobParameters params) {
        // Note: return true to reschedule this job.

        Log.d(TAG, "onStopJob id=" + params.getJobId());
       boolean shouldReschedule = false; //  updateTask.stopJob();

        return shouldReschedule;
    }

    private class UpdateAppsAsyncTask extends AsyncTask<JobParameters, Void, JobParameters[]>
    {

        @Override
        protected JobParameters[] doInBackground(JobParameters... params) {

            // Do updating and stopping logical here.
            Log.d(TAG, "Updating apps in the background");
            return params;
        }

        @Override
        protected void onPostExecute(JobParameters[] result) {
            for (JobParameters params : result) {
                if (!hasJobBeenStopped(params)) {
                    Log.d(TAG, "finishing job with id=" + params.getJobId());
                    jobFinished(params, false);
                }
            }
        }

        private boolean hasJobBeenStopped(JobParameters params) {
            // Logic for checking stop.
            return false;
        }

        public boolean stopJob(JobParameters params) {
            Log.d(TAG, "stopJob id=" + params.getJobId());
            // Logic for stopping a job. return true if job should be rescheduled.
            return false;
        }

    }

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

    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.d("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");

                    int notifId = 100;

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

                    showNotification(getApplicationContext(), "title", message, notifId);

                }

                else
                {
                    // erreur
                }
            }

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

            return("toto");
        }

        protected void onPostExecute(String s)
        {


        }
    }

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

    private void showNotification(Context context, String title, String message, int notifId)
    {

        int num = (int) System.currentTimeMillis();

        NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setSmallIcon(R.drawable.ic_replay_30_black_36dp)
                .setContentText(message)
                .setColor(ContextCompat.getColor(context, android.R.color.black))
                //.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setSound(alarmSound);
      //  notificationManagerCompat.notify(notifId, builder.build());

        notificationManagerCompat.notify(num, builder.build());
    }

    public static void cancelNotification(Context ctx, int notifyId) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
        nMgr.cancel(notifyId);
    }

}