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


/**
 * @projectName（项目名称）: xiaomi label
 * @package（包）: ui
 * @className（类名称）: AlarmAlertActivity
 * @description（类描述）: 继承了Activity类，该类实现了OnClickListener和 OnDismissListener两个接口，其中OnClickListener接口用来监听点击事件，OnDismissListener接口用来监听关闭对话框事件
 * @author（创建人）: zhangchaoqun
 * @createDate（创建时间）: datetime
 * @updateUser（修改人）: user
 * @updateDate（修改时间）: datetime
 * @updateRemark（修改备注）: 说明本次修改内容
 * @version（版本）: v1.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;


    /**
     * @description 描述: 消息响应函数，是用来“表示一个窗口正在生成”，这部分就是弹出对话框，播放闹铃
     * @param 参数1:savedInstanceState
     * @param 参数2:
     * @param 参数3:
     * @return 返回值:void
     * @author zhangchaoqun
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //从onCreate的参数savedInsanceState中获得状态数据
        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();

        try {
            /*
             *根据ID从数据库中获取标签的内容
             * getContentResolver（）是实现数据共享，实例存储
             */
            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;
        }
        /*
        try
        {
        	// 代码区
        }
        catch(Exception e)
        {
        	// 异常处理
        }
        代码区如果有错误，就会返回所写异常的处理。*/

        mPlayer = new MediaPlayer();
        if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
            //弹出对话框
            showActionDialog();
            //闹钟提示音激发
            playAlarmSound();
        } else {
            //完成闹钟动作
            finish();
        }
    }


    /**
     * @description 描述:定义了一个布尔类型的函数isScreen（）返回屏幕是否是亮的
     * @param 参数1:
     * @param 参数2:
     * @param 参数3:
     * @return 返回值:bool 判断屏幕是否亮起
     * @author zhangchaoqun
     */
    private boolean isScreenOn() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }


    /**
     * @description 描述:定义了一个播放铃声的函数playAlarmSound
     * @param 参数1:
     * @param 参数2:
     * @param 参数3:
     * @return 返回值:void
     * @author zhangchaoqun
     */
    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 {
            //setDataSource(Context context, Uri uri)，无返回值，设置多媒体数据来源【根据 Uri】
            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();
        }
    }


    /**
     * @description 描述:定义了一个显示动作窗口函数showActionDialog
     * @param 参数1:
     * @param 参数2:
     * @param 参数3:
     * @return 返回值:void
     * @author zhangchaoqun
     */
    private void showActionDialog() {
        //创建一个AlertDialog，要用到AlertDialog.Builder中的create()方法
        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);
    }


    /**
     * @description 描述:定义一个onClick函数用来处理鼠标点击事件
     * @param 参数1:dialog 对话框
     * @param 参数2:which 定位
     * @param 参数3:
     * @return 返回值:void
     * @author zhangchaoqun
     */
    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);
                //实现key-value对
                //EXTRA_UID为key；mNoteId为键
                intent.putExtra(Intent.EXTRA_UID, mNoteId);
                //开始动作
                startActivity(intent);
                break;
            //确定操作
            default:
                break;
        }
    }


    /**
     * @description 描述:窗口关闭监听器接口
     * @param 参数1:dialog
     * @param 参数2:
     * @param 参数3:
     * @return 返回值:void
     * @author zhangchaoqun
     */
    public void onDismiss(DialogInterface dialog) {
        //停止闹钟声音
        stopAlarmSound();
        //完成该动作
        finish();
    }


    /**
     * @description 描述:关闭闹钟铃声
     * @param 参数1:
     * @param 参数2:
     * @param 参数3:
     * @return 返回值:void
     * @author zhangchaoqun
     */
    private void stopAlarmSound() {
        if (mPlayer != null) {
            //停止播放
            mPlayer.stop();
            //释放MediaPlayer对象
            mPlayer.release();
            mPlayer = null;
        }
    }
}
