package com.jkanetwork.st.calendariodefrases;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.util.Calendar;
import android.os.PowerManager;
import android.util.Log;


/**
 * Created by http://stackoverflow.com/questions/4459058/alarm-manager-example
 * Modified by kprkpr
 */

public class Alarm extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();
        // Make notification appear
        context.startService(new Intent(context, NotificationHelper.class));

        wl.release();
    }

    public void putAlarm(Context context){
        Config conf = new Config(context);

        /* Common vars for alarm config */
        Intent i = new Intent(context, Alarm.class);
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent sender = PendingIntent.getBroadcast(context, 1, i, 0);

        /* Cancel alarm first */
        alarmMgr.cancel(sender);

        if (conf.getNotifOn() && !conf.getPersistNotifOn()){
            /* Here set the alarm to one time a day in selected date. Default: 8AM */
            Calendar time = Calendar.getInstance();
            /* Shedechule Alarm for tomorrow instead before now if alarm set to before. */
            if (Calendar.HOUR_OF_DAY > conf.getHour() || (Calendar.HOUR_OF_DAY == conf.getHour() && Calendar.MINUTE > conf.getMinute() )){
                /* Add a day */
                time.add(Calendar.DATE, 1);
            }
            time.set(Calendar.HOUR_OF_DAY, conf.getHour());
            time.set(Calendar.MINUTE, conf.getMinute());
            time.set(Calendar.SECOND, 0);
            Log.d("Next notification show",String.valueOf(time.getTime()));
            alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), 1000*3600*24, sender); // Repeat every day
        }

        if (conf.getNotifOn() && conf.getPersistNotifOn()){
            /* Here set the alarm to one time a day in selected date. Default: 8AM */
            Calendar time = Calendar.getInstance();
            /* Set for 0:00:01 of next day */
            time.add(Calendar.DATE, 1);
            time.set(Calendar.HOUR_OF_DAY, 0);
            time.set(Calendar.MINUTE, 0);
            time.set(Calendar.SECOND, 1);
            Log.d("Next notification show",String.valueOf(time.getTime()));
            alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), 1000*3600*24, sender); // Repeat every day
            context.startService(new Intent(context, NotificationHelper.class)); /* Auto start service for show notif */
        }
    }

}