package com.example.patrice.appli_04;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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.Calendar;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

    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;

   // public final async_requete_restitution aaa = new async_requete_restitution();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //debug coco = new debug();
        //coco.debug();

        //async_requete_restitution aqw = new async_requete_restitution();
        //aqw.async_requete_restitution();

        SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("PREFERENCE", 0); // 0 - for private mode
        Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE) .getBoolean("isFirstRun", true);
        //   RESET pour le debug
        //   getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit() .putBoolean("isFirstRun", true).commit();

/*
        Calendar cal = Calendar.getInstance();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);      // 0 to 11
        int day = cal.get(Calendar.DAY_OF_MONTH);

        long temps_actuel = 0;
        temps_actuel = 	cal.getTimeInMillis();
*/
        Calendar calendar = Calendar.getInstance();
        int current_day = calendar.get(Calendar.DAY_OF_WEEK);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);

        Calendar cal_build_date = Calendar.getInstance();
        cal_build_date.set(Calendar.YEAR, year);
        cal_build_date.set(Calendar.DAY_OF_MONTH, day);
        cal_build_date.set(Calendar.MONTH, month);
        cal_build_date.set(Calendar.HOUR_OF_DAY, 0);
        cal_build_date.set(Calendar.MINUTE, 0);
        cal_build_date.set(Calendar.SECOND, 0);
        cal_build_date.set(Calendar.MILLISECOND, 0);
        Date Date_date =  cal_build_date.getTime();
        long mili = cal_build_date.getTimeInMillis(); //   /1000

        // add days to current date
        int daysToAdd = 4;
        int daysToSubtract = 10;

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, daysToAdd);
// 4 mai à 3 Mai
        long res = 1525384800 - 1525298400;

        // vendredi 25 Mai

        long step = 1527199200 + (14 * 86400);

// https://phpcodeur.net/articles/php/dates
// http://www.expertphp.in/article/how-to-convert-php-timestamp-to-date-format-with-example
// https://www.guru99.com/php-date-functions.html
// http://webdevzoom.com/time-mktime-strtotime-function-php/

       // isFirstRun = true;

        if (isFirstRun)
        {
            /************ lancement du service de mise à jour du statut  ***********************/
            Intent intent = new Intent(this, appli_alarm_service.class);
            startService(intent);
            PendingIntent pendingIntent = PendingIntent .getService(this, 0, intent, 0);
            AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            long alarmStartTime = System.currentTimeMillis();
           // alarmStartTime = SystemClock.elapsedRealtime();
            long alarmExecuteInterval = 60*1000;

            long delayed = alarmExecuteInterval;
            long start_time = alarmStartTime + alarmExecuteInterval;

            alarm.setRepeating(AlarmManager.RTC_WAKEUP, start_time ,  alarmExecuteInterval, pendingIntent); // RTC_WAKEUP // ELAPSED_REALTIME_WAKEUP

            Log.v("*********", "First run Alarm Settings ");
            Toast.makeText(MainActivity.this, "Initialisation , premier lancement de l'appli ..", Toast.LENGTH_LONG).show();

            sharedpreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean("isFirstRun", false);
            editor.commit();

            /**********************************************************************************/
        }


      //  async_requete_restitution_jeu titi = new async_requete_restitution_jeu();

      //  titi.execution_async();


        //isMyServiceRunning(MyService.class);

    //boolean alarmUp0 = (PendingIntent.getBroadcast(MainActivity.this, 0,   new Intent("com.example.patrice.appli_03"),  PendingIntent.FLAG_NO_CREATE) != null);

    //    Boolean alarmUp3 = (PendingIntent.getBroadcast(MainActivity.this, 0,  new Intent("com.example.patrice.appli_03"),   PendingIntent.FLAG_UPDATE_CURRENT) != null);

  //Boolean alarmUp1 = (PendingIntent.getBroadcast(MainActivity.this, 234324243,  new Intent("com.example.patrice.boot_01"),    PendingIntent.FLAG_NO_CREATE) != null);

  //Boolean alarmUp2 = (PendingIntent.getBroadcast(MainActivity.this, 0,  new Intent("com.example.patrice.appli_02"),    PendingIntent.FLAG_NO_CREATE) != null);



      //  Boolean alarmUp1 = (PendingIntent.getBroadcast(MainActivity.this, 234324243,  new Intent("com.example.patrice.boot_01"),    PendingIntent.FLAG_UPDATE_CURRENT) != null);

      //  Boolean alarmUp2 = (PendingIntent.getBroadcast(MainActivity.this, 0,  new Intent("com.example.patrice.appli_02"),    PendingIntent.FLAG_UPDATE_CURRENT) != null);

 //       boolean alarmUp = (PendingIntent.getBroadcast(MainActivity.this, 0,   new Intent("com.example.patrice.appli_02"),  PendingIntent.FLAG_UPDATE_CURRENT) != null);

  //      boolean alarmUp1 = (PendingIntent.getBroadcast(MainActivity.this, 0,   new Intent("com.example.patrice.appli_05"),  PendingIntent.FLAG_UPDATE_CURRENT) != null);

    // https://exceptionshub.com/how-to-check-if-alarmmanager-already-has-an-alarm-set.html
/*
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
        {

            String ref = "com.example.patrice.appli_02";

            String compare = service.service.getClassName();

            if (ref.equals(service.service.getClassName()))
            {
                Log.v("*********", "Bingo");
            }
        }


        List<PackageInfo> pkgs = getPackageManager().getInstalledPackages(PackageManager.GET_SERVICES);

        for(PackageInfo pkg : pkgs)
        {

            String s = pkg.packageName;
            Log.v("*********", s);
            // You can now use pkg.services
        }


        String toto = "64";

        isServiceRunning("com.example.patrice.boot_01");

*/


    }

/*
    private boolean isServiceRunning()
    {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
        {
            if("com.example.MyNeatoIntentService".equals(service.service.getClassName()))
            {
                return true;
            }
        }
        return false;
    }

    private boolean isMyServiceRunning(Class<?> serviceClass)
    {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
        {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
*/
    public boolean isServiceRunning(String serviceClassName)
    {
        final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        final List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (ActivityManager.RunningServiceInfo runningServiceInfo : services)
        {

            String aaa = runningServiceInfo.service.getClassName();

            Log.v("*** ----  ***  ", aaa);

            if (runningServiceInfo.service.getClassName().equals(serviceClassName))

            if(serviceClassName.equals(aaa))
            {
                Log.v("+++++", "Cotronopipo ...........");
                return true;
            }
        }
        return false;
    }

/*
    private boolean ttttt() {
        ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (AlarmService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
*/
    /*************************************************************************************/

    class async_requete_restitution_jeu 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.d("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);
                        liste_jeu_notification.add(jeu);
                    }

                }

                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.d(" HTTP ******* ", message);
                    */
                }

                else
                {
                    // erreur non prévu
                }
            }

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

            return("toto");
        }

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

            int a = 5;
            a = a + 7;

        }
    }

}
