package com.efounder.chat.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.StorageUtil;

import java.io.IOException;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * Created by hudq on 2016/9/2. 铃声震动工具类
 */

public class RingVibratorUtils {
    private static MediaPlayer mediaPlayer;
    private static StorageUtil storageUtil = new StorageUtil(AppContext.getInstance(), "RingVibratorUtils");

    private static boolean isRinging = storageUtil.getBoolean("hasTones", true);
    private static boolean isVibrate = storageUtil.getBoolean("hasVibrator", true);

    private static long currentTimeMillis;

    /****
     * 震动
     */
    private static void vibrate(Context context) {
        //如果　isVibrate &&　不是静音模式
        if (isVibrate && ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
            Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            //震动一次
            vibrator.vibrate(300);
        }
    }

    /**
     * 响铃
     */
    private static void ringing(Context context) {
        //如果当前是铃音模式，播放提示声音
        if (isRinging && ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
            if (mediaPlayer == null) {
                mediaPlayer = getMediaPlayer(context);
            }
            mediaPlayer.start();
        }
    }

    public static void RingingAndVibrate(Context context, IMStruct002 imStruct002) {
        if (isShouldRingingAndVibrate(imStruct002)) {
            vibrate(context);
            ringing(context);
            currentTimeMillis = System.currentTimeMillis();
        }
    }

    /**
     * 是否应该响铃震动
     *
     * @param imStruct002
     * @return
     */
    private static boolean isShouldRingingAndVibrate(IMStruct002 imStruct002) {
        // 如果有@我的消息，则开启震动声音提醒
        if (TextFormatMessageUtil.checkHasAtMe(imStruct002)) {
            return true;
        }
        if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            //如果消息来自自己（一个帐号登录两个设备）
            return false;
        }
        if (imStruct002.getOffline() == 1) {//如果是离线消息
            return false;
        }
        if (isSetNoBother(imStruct002)) {
            return false;
        }
        if ((System.currentTimeMillis() - currentTimeMillis) < 500) {//每500毫秒震动响铃一次
            return false;
        }
        return true;
    }

    /**
     * 该群 或者该人的消息是否设置免打扰
     *
     * @param imStruct002
     * @return
     */
    private static boolean isSetNoBother(IMStruct002 imStruct002) {
        if (imStruct002.getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {
            Group group = WeChatDBManager.getInstance().getGroup(imStruct002.getToUserId(), false);
            if (group != null && group.getIsBother()) {
                return true;
            } else {
                return false;
            }

        }
        if (imStruct002.getToUserType() == StructFactory.TO_USER_TYPE_PERSONAL) {
            User user = WeChatDBManager.getInstance().getOneUserById(imStruct002.getFromUserId());
            if (user != null && user.getIsBother()) {
                return true;
            } else {
                return false;
            }
        }

        return false;
    }


    private static MediaPlayer getMediaPlayer(Context context) {
        //4.初始化MediaPlayer对象，指定播放的声音 通道为 STREAM_MUSIC
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //注册事件。当播放完毕一次后，重新指向流文件的开头，以准备下次播放。
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer player) {
                player.seekTo(0);
            }
        });
        //设定数据源，并准备播放
        AssetFileDescriptor file = context.getResources().openRawResourceFd(
                R.raw.reminder);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(),
                    file.getStartOffset(), file.getLength());
            file.close();
            //设置音量
            mediaPlayer.setVolume(0.5f, 0.5f);
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaPlayer;
    }

    public static void turnOnRing(boolean isTurnOn) {
        isRinging = isTurnOn;
        storageUtil.putBoolean("hasTones", isTurnOn);
        storageUtil.commit();
    }

    public static void turnOnVibrator(boolean isTurnOn) {
        isVibrate = isTurnOn;
        storageUtil.putBoolean("hasVibrator", isTurnOn);
        storageUtil.commit();
    }

    public static boolean isVibrate() {
        return isVibrate;
    }

    public static boolean isRinging() {
        return isRinging;
    }
}
