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


    //onCreate() 函数在 Activity 初始化时调用，用于初始化
    //savedInstanceState 该参数用于恢复 Activity 状态。
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //界面显示：无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //获取 Window 对象，添加 FLAG_SHOW_WHEN_LOCKED 标记
        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 intent = getIntent();

        //从Intent对象中获取笔记的 Id 和内容
        try {
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));

            //根据便签Id从数据库中获取便签内容
            //getContentResolver() 实现数据共享，实例存储
            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;
        }

        //创建 MediaPlayer 对象，根据笔记是否存在数据库中来展示操作对话框或者直接退出
        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 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() 函数功能是抛出异常，还将显示出更深的调用信息
            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();
        }
    }


    //创建一个对话框，标题为app的名字，内容为mSnippet，确定按钮为notealert_ok，
    // 当屏幕开启时，取消按钮为notealert_enter，点击弹出框外部可以隐藏弹出框
    private void showActionDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        //为对话框设置标题
        dialog.setTitle(R.string.app_name);
        //为对话框设置内容
        dialog.setMessage(mSnippet);
        //给对话框添加“OK”按钮
        dialog.setPositiveButton(R.string.notealert_ok, this);

        if (isScreenOn()) {
            //给对话框添加“CANCEL”按钮
            dialog.setNegativeButton(R.string.notealert_enter, this);
        }
        //给对话框设置监听器
        dialog.show().setOnDismissListener(this);
    }

    //当对话框界面内某个按钮被点击时调用以下方法
    // 接收 对话框界面 和 点击的按钮位置which 为参数
    public void onClick(DialogInterface dialog, int which) {
        //switch语句，根据按钮位置的不同，执行不同的操作
        switch (which) {
            //当点击点击的是返回按键
            case DialogInterface.BUTTON_NEGATIVE:
                //将编辑的便签内容传输到特定类中
                Intent intent = new Intent(this, NoteEditActivity.class);
                //设置操作属性
                intent.setAction(Intent.ACTION_VIEW);
                //创建一个特定的Note Id传输给便签
                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();
            //释放 MediaPlayer(媒体播放器)对象
            mPlayer = null;
        }
    }
}
