package com.rv.im;

import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.ruiwenliu.wrapper.MessageEventRemoteLogin;
import com.rv.im.broadcast.MessageReceiver;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.CallTypeEnum;
import com.rv.im.listener.AbstractMsgListener;
import com.rv.im.log.LogUtil;
import com.rv.im.util.NetworkUtil;
import com.rv.im.xmpp.ListenerManager;
import com.rv.im.xmpp.NotifyConnectionListener;
import com.rv.im.xmpp.ReceiptManager;
import com.rv.im.xmpp.XChatManager;
import com.rv.im.xmpp.XmppConnectionManager;
import com.rv.im.xmpp.listener.AuthStateListener;
import com.rv.im.xmpp.listener.ChatMessageListener;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.XMPPConnection;

import java.util.UUID;

public class ImService extends Service {

    private static final String TAG = ImService.class.getSimpleName();
    private static final Intent SERVICE_INTENT = new Intent();
    private XmppConnectionManager mConnectionManager;// 唯一
    private boolean isInit = true;
    private String mLoginUserId;
    private String mLoginPassword;
    private String mLoginNickName;

    private XChatManager mXChatManager;// 唯一
    private ReceiptManager mReceiptManager;// 唯一

    public String getUserId() {
        return mLoginUserId;
    }

    public static Intent getIntent() {
        return SERVICE_INTENT;
    }

    private MessageReceiver receiver = new MessageReceiver(new AbstractMsgListener() {
        @Override
        public void send(String toUserId, String message) {
            ChatMessage chatMessage = ChatMessage.json2Message(message);
            sendChatMessage(toUserId, chatMessage);
        }
    });

    private NotifyConnectionListener mNotifyConnectionListener = new NotifyConnectionListener() {
        @Override
        public void notifyConnecting() {
            LogUtil.e(TAG, "xmpp:notifyConnecting");
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_ING);
        }

        @Override
        public void notifyConnected(XMPPConnection arg0) {
            LogUtil.e(TAG, "xmpp:notifyConnected");
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_ING);
        }

        @Override
        public void notifyAuthenticated(XMPPConnection arg0) {
            LogUtil.e(TAG, "xmpp:notifyAuthenticated");
            onAuthenticated();
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_SUCCESS);// 通知登陆成功
            getLastChatHistory();
        }

        @Override
        public void notifyConnectionClosedOnError(Exception e) {

            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_NOT);
            LogUtil.e(TAG, "xmpp:notifyConnectionClosedOnError");
            Log.e(TAG, "连接异常==" + e.getMessage());
            if (e.getMessage().contains("conflict")) {
                Log.e(TAG, "连接异常==被挤下线了");
                EventBus.getDefault().post(new MessageEventRemoteLogin());
            } else {
                init();
            }
        }

        @Override
        public void notifyConnectionClosed() {
            LogUtil.e(TAG, "xmpp:notifyConnectionClosed");
            ListenerManager.getInstance().notifyAuthStateChange(AuthStateListener.AUTH_STATE_NOT);
        }
    };

    private ImServiceBinder mBinder = new ImServiceBinder();

    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.d(TAG, "ImService onBind");
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerReceiver();

        mLoginUserId = ImSetting.getUserId();
        mLoginPassword = ImSetting.getUserPassword();
        mLoginNickName = ImSetting.getUserName();
        init();
    }

    private void init() {
        if (mConnectionManager == null) {
            initConnection();
        }
        Log.e("zq", "isInit==true,直接登录");
        login(mLoginUserId, mLoginPassword);
        return;
    }

    private void onAuthenticated() {
        if (!isAuthenticated()) {
            return;
        }

        /* 消息回执管理 */
        if (mReceiptManager == null) {
            mReceiptManager = new ReceiptManager(this, mConnectionManager.getConnection());
        } else {
            mReceiptManager.reset();
        }

        // 初始化消息处理
        if (mXChatManager == null) {
            mXChatManager = new XChatManager(this, mConnectionManager.getConnection());
        } else {
            mXChatManager.reset();
        }

        /*  获取离线消息 */
        mConnectionManager.sendOnLineMessage();
    }

    public boolean isAuthenticated() {
        if (mConnectionManager != null && mConnectionManager.isAuthenticated()) {
            return true;
        }
        return false;
    }

    public void initConnection() {
        mConnectionManager = new XmppConnectionManager(this, mNotifyConnectionListener);
    }

    public void login(String userId, String password) {
        if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(password) && mConnectionManager != null) {
            mConnectionManager.login(userId, password);
        }
    }


    public void getLastChatHistory() {
    }


//    // 发送上线、检测消息
//    public void sendOnLineMessage() {
//        ChatMessage chatMessage = new ChatMessage();
//        chatMessage.setMessageType(XmppMessage.TYPE_SEND_ONLINE_STATUS);
//
//        chatMessage.setFromUserId(mLoginUserId);
//        chatMessage.setFromUserName(mLoginNickName);
//        chatMessage.setToUserId(mLoginUserId);
//        chatMessage.setContent("1");// 0 离线 1 在线
//
//        chatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
//        sendChatMessage(mLoginUserId, chatMessage);
//    }


    /********
     * 发送忙线消息
     * @param messageType
     * @param toUserId
     */
    public void sendBusyMessage(int messageType, String toUserId) {

        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setMessageType(messageType);
        chatMessage.setCallType(CallTypeEnum.CALL_BUSY);
        chatMessage.setFromUserId(mLoginUserId);
        chatMessage.setFromUserName(mLoginNickName);
        chatMessage.setToUserId(toUserId);
        chatMessage.setContent("对方忙线");
        chatMessage.setTimeSend(System.currentTimeMillis());
        chatMessage.setPackId(UUID.randomUUID().toString().replaceAll("-", ""));
        sendChatMessage(toUserId, chatMessage);
    }


    public class ImServiceBinder extends Binder {
        public ImService getService() {
            return ImService.this;
        }
    }

    /******
     * 注册接受消息的广播
     */
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTIONS.ACTION_SEND_RECEIVER);
        registerReceiver(receiver, intentFilter);
    }

    private void release() {
        if (mConnectionManager != null) {
            mConnectionManager.release();
            mConnectionManager = null;
        }

        mReceiptManager = null;
        mXChatManager = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();

        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    public void logout() {
        isInit = false;
        if (mConnectionManager != null) {
            mConnectionManager.logout();
        }
        stopSelf();
    }

    /**
     * 发送聊天消息
     */
    public void sendChatMessage(String toUserId, ChatMessage chatMessage) {
        if (mXChatManager == null) {
            LogUtil.e(TAG, "mXChatManager==null");
        }

        if (mReceiptManager == null) {
            LogUtil.e(TAG, "mReceiptManager==null");
        }

        if (!isAuthenticated()) {
            Log.e(TAG, "isAuthenticated==false");
            ListenerManager.getInstance().notifyMessageSendStateChange(chatMessage.getPackId(), ChatMessageListener.MESSAGE_SEND_FAILED);
            return;
        }

        if (mXChatManager == null || mReceiptManager == null
                || (!isAuthenticated() && !NetworkUtil.isNetworkAvailable(getApplicationContext()))) {
            ListenerManager.getInstance().notifyMessageSendStateChange(chatMessage.getPackId(), ChatMessageListener.MESSAGE_SEND_FAILED);
        } else {
            /**
             * 先添加一个等待接收回执的消息
             * 然后再发送这条消息
             */
            mReceiptManager.addWillSendMessage(toUserId, chatMessage, ReceiptManager.SendType.NORMAL, chatMessage.getContent());
            mXChatManager.sendMessage(toUserId, chatMessage);
        }
    }
}
