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 {
    // 笔记ID和摘要
    private long mNoteId;
    private String mSnippet;
    // 摘要预览最大长度
    private static final int SNIPPET_PREW_MAX_LEN = 60;
    // 媒体播放器，用于播放闹钟声音
    MediaPlayer mPlayer;

    @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);
        }

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

        try {
            // 从Intent数据中解析笔记ID
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
            // 获取笔记摘要内容
            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 {
            // 笔记不存在则关闭Activity
            finish();
        }
    }

    /**
     * 检查屏幕是否开启
     * @return 屏幕开启状态
     */
    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) {
        switch (which) {
            // 点击"进入"按钮
            case DialogInterface.BUTTON_NEGATIVE:
                // 启动笔记编辑Activity并传递笔记ID
                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();
        // 关闭Activity
        finish();
    }

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