/*
 * 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;
/*
author:刘瑞轩
日期：2023-4-12
*/

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) {
        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//在锁定状态下唤醒屏幕。如果该标志被设置，则当 Activity 启动时，系统将唤醒设备并点亮屏幕。
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON//允许在屏幕常亮时锁定设备。
                    | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);//允许布局扩展到屏幕装饰区域（例如状态栏）之下。
        }

        Intent intent = getIntent();//获取页面

        try {
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));//找到是否有对应的NoteId
            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，并将其赋值给 url 变量
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
        //获取当前系统中哪些音频流会受到静音模式的影响
        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
        //如果STREAM_ALARM受到影响，那么就将音频流形式设置为silentModeStreams
        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:
                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;
        }
    }
}
