package net.micode.notes.ui;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;

/**
 * @Package:        net.micode.notes.ui
 * @ClassName:      AlarmInitReceiver
 * @Description:
 * AlarmInitReceiver 是一个广播接收器（BroadcastReceiver）的类
 * 广播接收器是 Android 中常用的一种组件，用于接收并处理系统或应用发送的广播消息
 * @Author:         YangYizhe
 * @CreateDate:     12/21/2023 12:09 AM
 * @Version:        1.0
 */
public class AlarmInitReceiver extends BroadcastReceiver {
    private static final String [] PROJECTION = new String [] {
            NoteColumns.ID,
            NoteColumns.ALERTED_DATE
    };//对数据库的操作，调用标签ID和闹钟时间
    private static final int COLUMN_ID                = 0;
    private static final int COLUMN_ALERTED_DATE      = 1;

    @Override
    public void onReceive(Context context, Intent intent) {
        long currentDate = System.currentTimeMillis();//System.currentTimeMillis()产生一个当前的毫秒
        Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
                PROJECTION,
                NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
                new String[] { String.valueOf(currentDate) },
                null);//将long变量currentDate转化为字符串
        //Cursor在这里的作用是通过查找数据库中的标签内容，找到和当前系统时间相等的标签

        if (c != null) {
            if (c.moveToFirst()) {
                do {
                    long alertDate = c.getLong(COLUMN_ALERTED_DATE);
                    Intent sender = new Intent(context, AlarmReceiver.class);
                    sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
                    AlarmManager alermManager = (AlarmManager) context
                            .getSystemService(Context.ALARM_SERVICE);
                    alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
                } while (c.moveToNext());
            }
            c.close();
        }
    }
}