/*
 * 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.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;

import java.io.IOException;


public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
    
    private long mNoteId;           // 声明一个long类型的变量mNoteId
    private String mSnippet;        // 声明一个String类型的变量mSnippet
    private static final int SNIPPET_PREW_MAX_LEN = 60;     // 声明一个int类型的变量SNIPPET_PREW_MAX_LEN，值为60
    MediaPlayer mPlayer;            // 声明一个MediaPlayer类型的变量mPlayer

    
    @Override                       // 重写onCreate方法，用于初始化Activity
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  // 设置当前Activity的标题为空
        final Window win = getWindow();     // 获取当前Activity的Window对象
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);     // 设置当前Activity的Window对象的属性，使其在锁定状态时保持常亮

        if (!isScreenOn()) {        // 判断当前屏幕是否处于锁定状态
            win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON // 如果当前屏幕处于锁定状态，则设置当前Activity的Window对象的属性，使其在锁定状态时保持常亮，并允许锁定屏幕
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
        }

        Intent intent = getIntent();    // 获取当前Activity的Intent

        try {
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));  // 从Intent中获取mNoteId
            mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);    // 从数据库中获取mSnippet
            mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, // 如果mSnippet的长度大于SNIPPET_PREW_MAX_LEN，则截取mSnippet的前SNIPPET_PREW_MAX_LEN个字符，并加上getResources().getString(R.string.notelist_string_info)
                    SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
                    : mSnippet;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }

        mPlayer = new MediaPlayer();    // 初始化mPlayer
        
        if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {  // 判断mNoteId对应的Notes表中的TYPE_NOTE字段是否可见
            showActionDialog();     // 如果可见，则显示ActionDialog
            playAlarmSound();       // 播放闹钟音效
        } else {
            finish();               // 如果不可见，则结束当前Activity
        }
    }

    
    private boolean isScreenOn() {      // 判断当前屏幕是否处于锁定状态
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);   // 获取当前系统的PowerManager实例
        return pm.isScreenOn();         // 判断当前屏幕是否处于锁定状态
    }

    
    private void playAlarmSound() {     // 播放闹钟音效
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);    // 获取当前系统默认的闹钟铃声

        int silentModeStreams = Settings.System.getInt(getContentResolver(),    // 获取当前系统设置的静音模式
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {      // 判断当前系统设置的静音模式是否包含AudioManager.STREAM_ALARM
            mPlayer.setAudioStreamType(silentModeStreams);                      // 如果包含，则设置mPlayer的音频流类型为silentModeStreams
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);      // 如果不包含，则设置mPlayer的音频流类型为AudioManager.STREAM_ALARM
        }
        try {
            mPlayer.setDataSource(this, url);   // 设置mPlayer的数据源
            mPlayer.prepare();                  // 准备播放
            mPlayer.setLooping(true);           // 设置mPlayer循环播放
            mPlayer.start();                    // 开始播放
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    
    private void showActionDialog() {           // 显示ActionDialog
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);     // 创建一个AlertDialog.Builder实例
        dialog.setTitle(R.string.app_name);     // 设置AlertDialog的标题
        dialog.setMessage(mSnippet);            // 设置AlertDialog的消息
        dialog.setPositiveButton(R.string.notealert_ok, this);  // 设置AlertDialog的确定按钮
        if (isScreenOn()) {                     // 判断当前屏幕是否处于锁定状态
            dialog.setNegativeButton(R.string.notealert_enter, this);   // 如果当前屏幕处于锁定状态，则设置AlertDialog的取消按钮
        }
        dialog.show().setOnDismissListener(this);   // 显示AlertDialog
    }

    
    public void onClick(DialogInterface dialog, int which) {        // 重写onClick方法，用于处理用户点击Dialog中的按钮
        switch (which) {
            case DialogInterface.BUTTON_NEGATIVE:
                Intent intent = new Intent(this, NoteEditActivity.class);       // 创建一个Intent，用于启动NoteEditActivity
                intent.setAction(Intent.ACTION_VIEW);   // 设置Intent的action
                intent.putExtra(Intent.EXTRA_UID, mNoteId); // 设置Intent的参数
                startActivity(intent);      // 启动NoteEditActivity
                break;
            default:
                break;
        }
    }

    
    public void onDismiss(DialogInterface dialog) {     // 重写onDismiss方法，用于处理用户关闭Dialog
        stopAlarmSound();   // 停止播放闹钟音效
        finish();       // 结束当前Activity
    }

    
    private void stopAlarmSound() {     // 停止播放闹钟音效
        if (mPlayer != null) {          // 判断mPlayer是否为空
            mPlayer.stop();             // 如果不为空，则停止播放
            mPlayer.release();          // 释放mPlayer
            mPlayer = null;             // 将mPlayer置为空
        }
    }
}