/*
 * 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;

/**
 * 闹钟初始化接收器 - 负责重新设置所有待处理的笔记提醒
 * 当系统启动完成或时区变化时，该接收器会被触发，重新设置所有未来的笔记提醒
 */
public class AlarmInitReceiver extends BroadcastReceiver {

    // 查询投影 - 定义需要从数据库中获取的列
    private static final String [] PROJECTION = new String [] {
        NoteColumns.ID,          // 笔记ID
        NoteColumns.ALERTED_DATE // 提醒日期
    };

    // 列索引常量，用于从Cursor中获取数据
    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();
        
        // 查询数据库中所有未来的提醒（提醒时间大于当前时间且类型为笔记的记录）
        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
                    Intent sender = new Intent(context, AlarmReceiver.class);
                    // 设置Intent的数据URI，包含笔记ID
                    sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
                    
                    // 创建用于延迟执行的PendingIntent
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
                    
                    // 获取AlarmManager系统服务
                    AlarmManager alarmManager = (AlarmManager) context
                            .getSystemService(Context.ALARM_SERVICE);
                    
                    // 设置闹钟，在指定时间触发PendingIntent
                    alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
                    
                } while (c.moveToNext());
            }
            // 关闭Cursor，释放 资源
            c.close();
        }
    }
}
