package com.rv.im.xmpp;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;

import com.ruiwenliu.wrapper.util.AppUtils;
import com.rv.im.ImSetting;
import com.rv.im.R;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.rv.im.db.service.IChatMessageService;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.util.NotificationMananger;
import com.rv.im.xmpp.listener.AuthStateListener;
import com.rv.im.xmpp.listener.ChatMessageListener;

import java.util.ArrayList;
import java.util.List;

public class ListenerManager {
    private static ListenerManager instance;
    /* 回调监听 */
    private List<AuthStateListener> mAuthStateListeners = new ArrayList<>();
    private List<ChatMessageListener> mChatMessageListeners = new ArrayList<>();

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private ListenerManager() {
    }

    public static ListenerManager getInstance() {
        if (instance == null) {
            instance = new ListenerManager();
        }
        return instance;
    }

    public void reset() {
        instance = null;
    }

    /**********************
     * 注册和移除监听
     **************************/

    public void addAuthStateChangeListener(AuthStateListener authStateChangeListener) {
        mAuthStateListeners.add(authStateChangeListener);
    }

    public void removeAuthStateChangeListener(AuthStateListener authStateChangeListener) {
        mAuthStateListeners.remove(authStateChangeListener);
    }

    public void addChatMessageListener(ChatMessageListener messageListener) {
        mChatMessageListeners.add(messageListener);
    }

    public void removeChatMessageListener(ChatMessageListener messageListener) {
        mChatMessageListeners.remove(messageListener);
    }

    /**********************
     * 监听回调
     **************************/
    public void notifyAuthStateChange(final int authState) {
        if (mAuthStateListeners.size() <= 0) {
            return;
        }
        mHandler.post(() -> {
            for (AuthStateListener authStateChangeListener : mAuthStateListeners) {
                authStateChangeListener.onAuthStateChange(authState);
            }
        });
    }

    /**
     * 消息发送状态监听
     */
    public void notifyMessageSendStateChange(final String msgId, final int messageState) {
        switch (messageState) {
            case ChatMessageListener.MESSAGE_SEND_FAILED:
                getDbService().setMsgSendFailure(msgId);
                break;
            case ChatMessageListener.MESSAGE_SEND_SUCCESS:
                getDbService().setMsgSendSuccess(msgId);
                break;
        }

        mHandler.post(() -> {
            for (ChatMessageListener listener : mChatMessageListeners) {
                listener.onMessageSendStateChange(messageState, msgId);
            }
        });
    }

    private IChatMessageService getDbService() {
        return ChatMessageServiceImp.getInstance(ImSetting.getContext());
    }


    /**
     * 新消息来临
     */
    public void notifyNewMesssage(final ChatMessage message) {
        if (message == null) return;
        NotificationMananger.showNewsNotification(ImSetting.getContext(), message.getFromId());
        bell();
        mHandler.post(() -> {
            if (message != null) {
                ChatMessageServiceImp.getInstance(ImSetting.getContext()).addMessage(message);  // 数据库添加消息
                AppUtils.setBadger(ImSetting.getContext(),ChatMessageServiceImp.getInstance(ImSetting.getContext()).getUnReadMsg() );
                for (int i = mChatMessageListeners.size() - 1; i >= 0; i--) {
                    mChatMessageListeners.get(i).onNewMessage(message.getFromUserId(), message, false);
                }
            }
        });
    }

    private void bell() {
        MediaPlayer mediaPlayer = MediaPlayer.create(ImSetting.getContext(), R.raw.msg);
        mediaPlayer.start();
        mediaPlayer.setOnCompletionListener(arg0 -> {
            mediaPlayer.start();
            stopPlay(mediaPlayer);
        });
    }

    private void stopPlay(MediaPlayer mediaPlayer) {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mediaPlayer.release();
        }
    }
}
