package com.uit_252254.mr3chi.kltn;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

import com.uit_252254.mr3chi.kltn.models.Notification;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Mr3chi on 5/8/2015.
 */
public class NotificationHandler {

    public static final String EXTRA_NOTI_ID    = "ID";
    public static final String EXTRA_TITLE      = "TITLE";
    public static final String EXTRA_CONTENT    = "CONTENT";
    public static final String EXTRA_IS_MOMNOTIFICATION   = "MOM_NOT";

    public static ArrayList<PendingIntent> addAlarms(Context context, List<Notification> dataset){
        AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        ArrayList<PendingIntent> intentArray = new ArrayList<>();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean doNotification = prefs.getBoolean("notifications_do_notification", true);
        if(!doNotification) return null;

        for(int i = 0; i < dataset.size(); i++){
            Calendar calendar = Calendar.getInstance();
            if(calendar.getTimeInMillis() > dataset.get(i).getNotiTime().getTimeInMillis()){
                continue;
            }

            if(dataset.get(i).isDone()) continue;

            Intent intent = new Intent(context, NotificationReceiver.class);
            Bundle bundle = new Bundle();

            bundle.putLong(EXTRA_NOTI_ID, dataset.get(i).getId());
            bundle.putString(EXTRA_TITLE, dataset.get(i).getName());
            bundle.putString(EXTRA_CONTENT, dataset.get(i).getContent());
            boolean isMom = false;
            if(dataset.get(i).getKidId() == -1) isMom = true;
            bundle.putBoolean(EXTRA_IS_MOMNOTIFICATION, isMom);
            intent.putExtras(bundle);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int)dataset.get(i).getId(), intent, 0);
            mgrAlarm.set(AlarmManager.RTC_WAKEUP, dataset.get(i).getNotiTime().getTimeInMillis(), pendingIntent);
            intentArray.add(pendingIntent);
        }

        return intentArray;
    }

    public static void removeAlarmsById(Context context, long id){
        AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, NotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int)id, intent, 0);
        try {
            mgrAlarm.cancel(pendingIntent);
        } catch (Exception e) {
            Log.e("error", "");
        }
    }
}
