/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * 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 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;

/**
 * AlarmInitReceiver 是一个 BroadcastReceiver，用于初始化所有未来提醒的闹钟。
 * 它在系统启动或应用被触发时重新设置已存在的提醒笔记的闹钟。
 */
public class AlarmInitReceiver extends BroadcastReceiver {
/** 查询笔记表时使用的列投影（ID 和提醒时间） */
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;
/**
 * 接收到广播后执行的方法，用于初始化所有未来的闹钟提醒。
 *
 * - 查询所有设置了提醒时间且未过期的笔记
 * - 为每个笔记设置对应的闹钟 PendingIntent
 * - 使用 AlarmManager 设置 RTC_WAKEUP 类型的定时提醒
 *
 * @param context 上下文对象
 * @param intent  广播意图
 */
    @Override
    public void onReceive(Context context, Intent intent) {
        long currentDate = 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);

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