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

// 导入Android基础组件
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;

// 导入Android系统服务相关
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; // 用于存储便签ID
    private String mSnippet; // 用于存储便签摘要
    private static final int SNIPPET_PREW_MAX_LEN = 60; // 便签摘要的最大长度
    MediaPlayer mPlayer; // 用于播放闹钟声音的MediaPlayer对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏

        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 设置窗口在锁屏状态下显示

        if (!isScreenOn()) { // 如果屏幕未点亮，则设置相关标志以点亮屏幕
            win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
        }

        Intent intent = getIntent(); // 获取启动此活动的Intent

        try {
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 从Intent中获取便签ID
            mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 根据ID获取便签摘要
            mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
                    SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
                    : mSnippet; // 截取摘要并添加额外信息
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }

        mPlayer = new MediaPlayer(); // 创建MediaPlayer对象
        if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { // 检查便签是否可见
            showActionDialog(); // 显示操作对话框
            playAlarmSound(); // 播放闹钟声音
        } else {
            finish(); // 如果便签不可见，则结束活动
        }
    }

    private boolean isScreenOn() { // 检查屏幕是否点亮
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

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

        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); // 获取静音模式下受影响的音频流类型

        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { // 如果闹钟声音被静音，则设置MediaPlayer的音频流类型
            mPlayer.setAudioStreamType(silentModeStreams);
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        try {
            mPlayer.setDataSource(this, url); // 设置MediaPlayer的数据源
            mPlayer.prepare(); // 准备播放
            mPlayer.setLooping(true); // 设置循环播放
            mPlayer.start(); // 开始播放
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showActionDialog() { // 显示操作对话框
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.app_name); // 设置对话框标题
        dialog.setMessage(mSnippet); // 设置对话框消息
        dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮及其监听器
        if (isScreenOn()) {
            dialog.setNegativeButton(R.string.notealert_enter, this); // 如果屏幕已点亮，则设置取消按钮及其监听器
        }
        dialog.show().setOnDismissListener(this); // 显示对话框并设置关闭监听器
    }

    public void onClick(DialogInterface dialog, int which) { // 对话框按钮点击事件处理
        switch (which) {
            case DialogInterface.BUTTON_NEGATIVE:
                Intent intent = new Intent(this, NoteEditActivity.class);
                intent.setAction(Intent.ACTION_VIEW);
                intent.putExtra(Intent.EXTRA_UID, mNoteId);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    public void onDismiss(DialogInterface dialog) { // 对话框关闭事件处理
        stopAlarmSound(); // 停止闹钟声音
        finish(); // 结束活动
    }

    private void stopAlarmSound() { // 停止闹钟声音
        if (mPlayer != null) {
            mPlayer.stop(); // 停止播放
            mPlayer.release(); // 释放资源
            mPlayer = null; // 置空引用
        }
    }
}