/*
 * 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;     //文本在数据存储中的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);
        //Bundle 类型的数据与 Map类型的数据相似，都是以keu-value的形式存储数据的
        //on save InstanceState方法是用来保存Activity的状态的
        //能从onCreate的参数savedInsanceState中获得状态数据
        //不显示窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //获取当前窗口的Window实例，用于设置标志以在屏幕锁定时显示此Activity
        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的data中提取闹钟ID(mNoteId)和文本片段(mSnippet)
        try {
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
            mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
            //根据ID从数据库中获取标签的内容
            //getContentResolver()实现数据共享，实例存储
            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;
        }
        /*
        try
        {
        	// 代码区
        }
        catch(Exception e)
        {
        	// 异常处理
        }
                     代码区如果有错误，就会返回所写异常的处理。*/
        mPlayer = new 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
        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) {
            mPlayer.setAudioStreamType(silentModeStreams);
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        //尝试设置数据源，准备播放器，设置为循环播放，并开始播放
        try {
            mPlayer.setDataSource(this, url);
            mPlayer.prepare();
            mPlayer.setLooping(true);
            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() {
        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) {
        //如果点击了"查看"按钮，启动NoteEditActivity来查看并编辑便签
        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();
    }

    //停止并释放MediaPlayer资源
    private void stopAlarmSound() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }
}
