package com.bc_chat.im.service;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.text.TextUtils;

import com.bc_chat.bc_base.utils.Const;
import com.bc_chat.im.messages.systen.RCNoticeMessage;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zhaohaoting.framework.utils.notification.MessageNoticeManager;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import io.rong.common.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongNotificationManager;
import io.rong.imkit.model.ConversationInfo;
import io.rong.imkit.notification.MessageNotificationManager;
import io.rong.imkit.utils.NotificationUtil;
import io.rong.imkit.utils.SystemUtils;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.MentionedInfo;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.RecallNotificationMessage;

/**
 * author：Created by zhaohaoting on 2019/3/5
 * email：526309416@qq.com
 * desc：
 */
public class MyMessageNotificationManager {

    private MediaPlayer mediaPlayer;

    private static int PUSH_SERVICE_NOTIFICATION_ID = 2000;

    private static final String TAG = "MyMessageNotificationManager";

    private MyMessageNotificationManager() {
    }

    public static MyMessageNotificationManager getInstance() {
        return MyMessageNotificationManager.SingletonHolder.instance;
    }


    public void notifyIfNeed(final Context context, final Message message) {
        if (message.getContent().getMentionedInfo() != null) {
            MentionedInfo mentionedInfo = message.getContent().getMentionedInfo();
            if (mentionedInfo.getType().equals(MentionedInfo.MentionedType.ALL) || mentionedInfo.getType().equals(MentionedInfo.MentionedType.PART) && mentionedInfo.getMentionedUserIdList() != null && mentionedInfo.getMentionedUserIdList().contains(RongIMClient.getInstance().getCurrentUserId())) {
                this.notify(context, message);
                return;
            }
        }

        boolean quiet = MessageNotificationManager.getInstance().isInQuietTime();
        if (quiet) {
            RLog.d("MyMessageNotificationManager", "in quiet time, don't notify.");
        } else {
            if (message.getConversationType().equals(Conversation.ConversationType.ENCRYPTED)) {
                getInstance().notify(context, message);
            } else {
                RongIM.getInstance().getConversationNotificationStatus(message.getConversationType(), message.getTargetId(), new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                    public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                        if (conversationNotificationStatus.equals(Conversation.ConversationNotificationStatus.NOTIFY)) {
                            MyMessageNotificationManager.getInstance().notify(context, message);
                        }
                    }

                    public void onError(RongIMClient.ErrorCode e) {
                    }
                });
            }
        }
    }

    private void notify(Context context, Message message) {
        boolean isInBackground = SystemUtils.isInBackground(context);
        if (isInBackground) {
            if (message.getConversationType() != Conversation.ConversationType.CHATROOM) {
                MessageContent content = message.getContent();
                if (content instanceof RCNoticeMessage) {
                    try {
                        CommentPushEntity commentPushEntity = new Gson().fromJson(((RCNoticeMessage) content).getExtra(), CommentPushEntity.class);
                        Intent intent = new Intent();
                        switch (commentPushEntity.getType()) {
                            case Const.PushMethod.FOLLOW_LIST:
                                Uri.Builder builder = Uri.parse("rong://" + context.getPackageName()).buildUpon()
                                        .appendPath("conversationlist");
                                intent.setData(builder.build());
                                intent.setPackage(context.getPackageName());
                                intent.putExtra("action", Const.Action.CIRCLE_LIKE);
                                break;
                            case Const.PushMethod.TOPIC_COMMENT:
                                intent.setAction("com.bc_chat.circle.activity.TopicDetailsActivity");
                                intent.putExtra("cid", commentPushEntity.getCid());
                                intent.putExtra("commentId", commentPushEntity.getCommentId());
                                intent.putExtra("selection", commentPushEntity.getType());
                                break;
                            case Const.PushMethod.TOPIC_CHILD_COMMENT:
                                intent.setAction("com.bc_chat.circle.activity.TopicDetailsActivity");
                                intent.putExtra("cid", commentPushEntity.getCid());
                                intent.putExtra("commentId", commentPushEntity.getCommentId());
                                intent.putExtra("selection", commentPushEntity.getType());
                                break;
                        }
                        MessageNoticeManager.getInstance().makeNotification(context, "系统", ((RCNoticeMessage) content).getContent(), ((RCNoticeMessage) content).getContent(), intent, ++PUSH_SERVICE_NOTIFICATION_ID);
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            int ringerMode = NotificationUtil.getRingerMode(context);
            if (ringerMode != 0) {
                if (ringerMode != 1) {
                    this.sound();
                }

                this.vibrate();
            }
        }
    }


    private void sound() {
        Uri res = RingtoneManager.getDefaultUri(2);
        if (RongContext.getInstance().getNotificationSound() != null && !TextUtils.isEmpty(RongContext.getInstance().getNotificationSound().toString())) {
            res = RongContext.getInstance().getNotificationSound();
        }

        try {
            if (this.mediaPlayer != null) {
                this.mediaPlayer.stop();
                this.mediaPlayer.reset();
                this.mediaPlayer.release();
                this.mediaPlayer = null;
            }

            this.mediaPlayer = new MediaPlayer();
            this.mediaPlayer.setOnCompletionListener(mp -> {
                if (mp != null) {
                    try {
                        mp.stop();
                        mp.reset();
                        mp.release();
                    } catch (Exception var3) {
                        RLog.e("MessageNotificationManager", "sound", var3);
                    }
                }

                if (mediaPlayer != null) {
                    mediaPlayer = null;
                }

            });
            this.mediaPlayer.setAudioStreamType(2);
            this.mediaPlayer.setDataSource(RongContext.getInstance(), res);
            this.mediaPlayer.prepare();
            this.mediaPlayer.start();
        } catch (Exception var3) {
            RLog.e("MessageNotificationManager", "sound", var3);
            if (this.mediaPlayer != null) {
                this.mediaPlayer = null;
            }
        }

    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) RongContext.getInstance().getSystemService("vibrator");
        vibrator.vibrate(new long[]{0L, 200L, 250L, 200L}, -1);
    }

    private static class SingletonHolder {
        static final MyMessageNotificationManager instance = new MyMessageNotificationManager();

        private SingletonHolder() {
        }
    }
}
