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;
/**
 * @Package:        net.micode.notes.ui
 * @ClassName:      AlarmAlertActivity
 * @Description:    闹钟提醒界面
 * @Author:         YangYizhe
 * @CreateDate:     12/21/2023 12:02 AM
 * @Version:        1.0
 */
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;
    /**
     * @method  onCreate
     * @description 当 Activity 创建时调用的生命周期方法
     * @date: 12/21/2023 12:05 AM
     * @author: YangYizhe
     * @param savedInstanceState 保存 Activity 状态的 Bundle 对象
     * @return null
     */
    @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);
        }

        Intent intent = getIntent();//获取传递的 Intent

        try {
            // 从 Intent 中获取数据并处理——获取标签 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();// 结束当前 Activity
        }
    }
    /**
     * @method  isScreenOn
     * @description
     * 判断屏幕是否锁屏，调用系统函数判断，最后返回值是布尔类型
     * @date: 12/23/2023 11:21 PM
     * @author: YangYizhe
     * @param
     * @return
     */
    private boolean isScreenOn() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }
    /**
     * @method  playAlarmSound
     * @description
     * 播放闹钟提示音
     * @date: 12/23/2023 11:21 PM
     * @author: YangYizhe
     */
    private void playAlarmSound() {
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
        //调用系统的铃声管理URI，得到闹钟提示音
        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();
        }
    }
    /**
     * @method  showActionDialog
     * @description
     * AlertDialog的构造方法全部是Protected的
     * 所以不能直接通过new一个AlertDialog来创建出一个AlertDialog。
     * 要创建一个AlertDialog，就要用到AlertDialog.Builder中的create()方法
     * 如这里的dialog就是新建了一个AlertDialog
     * @date: 12/23/2023 11:28 PM
     * @author: YangYizhe
     */
    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);//给对话框添加"Yes"按钮
        if (isScreenOn()) {
            dialog.setNegativeButton(R.string.notealert_enter, this);//对话框添加"No"按钮
        }
        dialog.show().setOnDismissListener(this);
    }
    /**
     * @method  onClick
     * @description 处理点击事件
     * @date: 12/23/2023 11:27 PM
     * @author: YangYizhe
     * @param dialog
     * @param which
     */
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {//用which来选择click后下一步的操作
            case DialogInterface.BUTTON_NEGATIVE://这是取消操作
                Intent intent = new Intent(this, NoteEditActivity.class);//实现两个类间的数据传输
                intent.setAction(Intent.ACTION_VIEW);//设置动作属性
                intent.putExtra(Intent.EXTRA_UID, mNoteId);//实现key-value对     EXTRA_UID为key；mNoteId为键
                startActivity(intent);//开始动作
                break;
            default:
                break;
        }
    }
    /**
     * @method  onDismiss
     * @description 忽略
     * @date: 12/23/2023 11:25 PM
     * @author: YangYizhe
     * @param dialog
     */
    public void onDismiss(DialogInterface dialog) {
        stopAlarmSound();//停止闹钟声音
        finish();
    }
    /**
     * @method  stopAlarmSound
     * @description 停止闹钟的声音
     * @date: 12/23/2023 11:26 PM
     * @author: YangYizhe
     */
    private void stopAlarmSound() {
        if (mPlayer != null) {
            mPlayer.stop();//停止播放
            mPlayer.release();//释放MediaPlayer对象
            mPlayer = null;
        }
    }
}