/*
 * Copyright (c) 2015 Martin Norbert
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.site_monitor.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

import org.site_monitor.BuildConfig;
import org.site_monitor.activity.PrefSettingsActivity;
import org.site_monitor.service.DataStoreService;
import org.site_monitor.service.NetworkService;
import org.site_monitor.util.TimeUtil;

import java.util.Date;
import java.util.Random;

public class AlarmReceiver extends WakefulBroadcastReceiver {

    public static final String TAG = "AlarmReceiver";
    private static final Random RANDOM = new Random(new Date().getTime());

    private static PendingIntent pendingIntent;
    private static Long currentInterval;

    public static PendingIntent startAlarm(Context context) {
        if (hasAlarm()) {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "startAlarm: already set");
            }
            return pendingIntent;
        }
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "startAlarm");
        }
        String intervalString = PreferenceManager.getDefaultSharedPreferences(context).getString(PrefSettingsActivity.FREQUENCY, null);
        long interval = AlarmManager.INTERVAL_HOUR;
        if (intervalString != null) {
            interval = Long.parseLong(intervalString) * TimeUtil.MINUTE_2_MILLISEC;
        }

        return scheduleAlarm(context, interval);
    }

    public static void stopAlarm(Context context) {
        if (!hasAlarm()) {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "stopAlarm: already stopped");
            }
            return;
        }
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
        pendingIntent = null;
        currentInterval = null;
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "stop alarm");
        }
    }

    public static void rescheduleAlarm(Context context, Long newFrequency) {
        if (hasAlarm()) {
            stopAlarm(context);
        } else {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "rescheduleAlarm: none started");
            }
        }
        scheduleAlarm(context, newFrequency);
    }

    public static boolean hasAlarm() {
        return pendingIntent != null;
    }

    public static Long getCurrentInterval() {
        return currentInterval;
    }

    private static PendingIntent scheduleAlarm(Context context, long interval) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent newPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, interval, interval, newPendingIntent);
        currentInterval = interval / TimeUtil.MINUTE_2_MILLISEC;
        pendingIntent = newPendingIntent;
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "schedule alarm every: " + currentInterval + " (" + interval + ")");
        }
        saveNextAlarmDate(context);
        return pendingIntent;
    }

    private static void saveNextAlarmDate(Context context) {
        long intervalMilli = currentInterval * TimeUtil.MINUTE_2_MILLISEC;
        DataStoreService.saveNow(context, DataStoreService.KEY_NEXT_ALARM, System.currentTimeMillis() + intervalMilli);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            if (BuildConfig.DEBUG) {
                Log.i(TAG, "onReceive");
            }
            Thread.sleep(RANDOM.nextInt(10) * 100);
            WakefulBroadcastReceiver.startWakefulService(context, NetworkService.getIntent(context));

            saveNextAlarmDate(context);
        } catch (InterruptedException e) {
            if (BuildConfig.DEBUG) {
                Log.wtf(TAG, e);
            }
        }
    }

}

@@ -1450,16 +1450,109 @@
 erval;%0A%0A
+    /**%0A     * Starts alarm if none set.%0A     *%0A     * @param context%0A     * @return%0A     */%0A
     publ
@@ -1785,88 +1785,8 @@
   %7D%0A
-        if (BuildConfig.DEBUG) %7B%0A            Log.i(TAG, %22startAlarm%22);%0A        %7D
 %0A   
@@ -1914,24 +1914,126 @@
 NCY, null);%0A
+        if (intervalString == null %7C%7C intervalString.isEmpty()) %7B%0A%0A            return null;%0A        %7D%0A
         long
@@ -2106,16 +2106,45 @@
  != null
+ && !intervalString.isEmpty()
 ) %7B%0A    
@@ -2224,33 +2224,266 @@
 LISEC;%0A        %7D
-%0A
+ else %7B%0A            if (BuildConfig.DEBUG) %7B%0A                Log.w(TAG, %22intervalString is null, default interval: %22 + interval);%0A            %7D%0A        %7D%0A        if (BuildConfig.DEBUG) %7B%0A            Log.i(TAG, %22startAlarm%22);%0A        %7D
 %0A        return 
@@ -4636,24 +4636,58 @@
 t intent) %7B%0A
+        if (intent != null) %7B%0A    
         try 
@@ -4688,16 +4688,20 @@
   try %7B%0A
+    
         
@@ -4737,32 +4737,36 @@
                 
+    
 Log.i(TAG, %22onRe
@@ -4778,34 +4778,42 @@
 %22);%0A            
+   
+ 
 %7D%0A
+    
             Thre
@@ -4848,16 +4848,20 @@
 * 100);%0A
+    
         
@@ -4950,25 +4950,25 @@
 (context));%0A
-%0A
+ 
             
@@ -4959,32 +4959,35 @@
 );%0A             
+   
 saveNextAlarmDat
@@ -4990,32 +4990,36 @@
 mDate(context);%0A
+    
         %7D catch 
@@ -5041,24 +5041,28 @@
 eption e) %7B%0A
+    
             
@@ -5098,24 +5098,28 @@
             
+    
 Log.wtf(TAG,
@@ -5123,16 +5123,34 @@
 AG, e);%0A
+                %7D%0A
         

fix null pointer on AlarmReceiver