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

                                //继承Activity            //承诺实现click，dismiss接口，不继承功能
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
    private long mNoteId;
    private String mSnippet;
    private static final int SNIPPET_PREW_MAX_LEN = 60;
    MediaPlayer mPlayer;

    @Override //创建闹钟行为
    protected void onCreate(Bundle savedInstanceState) {
        //调用其父类Activity的onCreate方法来实现对界面的图画绘制工作。
        super.onCreate(savedInstanceState);
        //onSaveInstanceState()来保存当前activity的状态信息
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //final类似stactic，获得窗口对象
        final Window win = getWindow();
        //为窗口添加各种标志（flags），从而改变窗口的行为和外观
        //屏幕锁定时显示窗口，便于锁屏时启动闹钟
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
                                  //LayoutParams 布局参数，规定子视图如何放置
        if (!isScreenOn()) {//不锁平时
            win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON//当这个window对用户是可见状态,则保持设备屏幕不关闭且不变暗
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON//当window被添加或者显示,系统会点亮屏幕,
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON//允许在屏幕开启的时候锁定屏幕
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);//插入window的矩形大小,来确保内容不会被装饰物(如状态栏)掩盖
        }

        Intent intent = getIntent();

        try {                       //传递到当前组件的 URI 数据，截取Uri内的字符串的第二个“/”右边的字符及id
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
            //根据ID从数据库中获取标签的内容
            mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
            //判断是否超过最大长度，超过执行截取操作
            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();
        //如果不在回收站就显示文字并发出声音
        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是对话框组件，用于显示信息
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.app_name);
        dialog.setMessage(mSnippet);
        dialog.setPositiveButton(R.string.notealert_ok, this);  //setPositive/Negative/NeutralButton()设置：确定，取消，中立按钮；
        if (isScreenOn()) {
            dialog.setNegativeButton(R.string.notealert_enter, this); //取消
        }
        dialog.show().setOnDismissListener(this); //设置关闭监听
    }
    //选择negative时执行跳转到笔记 （那可能positive仅关闭弹窗）
    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);//向目标页面传递笔记的ID
                startActivity(intent);//触发页面跳转
                break;
            default:
                break;
        }
    }
    //取消监听后操作
    public void onDismiss(DialogInterface dialog) {
        stopAlarmSound();
        finish();
    }
    //取消声音
    private void stopAlarmSound() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }
}
