/*
 * 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 {
    //该类继承于BroadcastReceiver类，该类主要用于对闹铃信息的接受，相关的类会使用sendBroadcast()方法发送的意图，
    // 该类重新实现了Onreceive（）方法，该方法实现对广播的侦听，由此实现对接受闹铃启动消息的功能。
    private static final String [] PROJECTION = new String [] {
        NoteColumns.ID,
        NoteColumns.ALERTED_DATE
    };//声明PROJECTION，每个元素包括id和提醒日期

    private static final int COLUMN_ID                = 0;
    private static final int COLUMN_ALERTED_DATE      = 1;
     //设置ID和默认时间初始值
    @Override
    public void onReceive(Context context, Intent intent) {  //接受广播后的处理过程
        long currentDate = System.currentTimeMillis();
        Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,//Cursor在这里的作用是通过查找数据库中的标签内容，找到和当前系统时间相等的标签
                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);//向Alarmreceiver发送时间信息
                    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();
        }
    }
}
