package net.openmob.mobileimsdk.android.core;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.renrenliao.im.im.ChatType;
import com.renrenliao.im.im.ImMsgBean;
import com.renrenliao.im.im.ImMsgFactory;
import com.renrenliao.im.im.SignInType;
import com.renrenliao.im.utils.CharsetUtils;
import com.renrenliao.im.utils.StringUtils;

import net.openmob.mobileimsdk.android.ClientCoreSDK;

import java.net.DatagramPacket;


class LocalDataHandler extends Handler {
    private static final String TAG = LocalDataHandler.class.getSimpleName();

    public LocalDataHandler(Looper looper) {
        super(looper);
    }

    public void handleMessage(Message msg) {
        DatagramPacket packet = (DatagramPacket) msg.obj;
        if (packet != null) {
            try {
                ImMsgBean pFromServer = ImMsgFactory.parse(packet.getData(), packet.getLength());
                if (ClientCoreSDK.DEBUG) {
                    Log.i("recallMessage", " pFromServer  " + CharsetUtils.getString(packet.getData(), packet.getLength()));
                }
             //   LocalDataSource.Companion.getTestLiveData().postValue(CharsetUtils.getString(packet.getData(), packet.getLength()));
               // Log.e(TAG,"主线程："+Looper.getMainLooper().getThread().getName()+" "+Looper.getMainLooper().getThread().getId()+"线程名:"+Thread.currentThread().getName()+"ID："+Thread.currentThread().getId());

                //IM服务器登录响应   0
                //上线通知   1
                //下线通知   2
                //收到回执   3
                //心跳      4
                //文本消息     5
                //普通消息     20
                if (pFromServer.getMsgType() == 0 || pFromServer.getMsgType() == 3 || pFromServer.getMsgType() == 4) {
                    if (ClientCoreSDK.DEBUG) {
                        Log.i(TAG, "【IMCORE】【BugFIX】这是服务端返回的响应包,本次无需发送ACK应答包! msgtype:" + pFromServer.getMsgType());
                    }
                } else {
                    if (QoS4ReciveDaemon.getInstance().hasRecieved(pFromServer.getFp())) {
                        if (ClientCoreSDK.DEBUG) {
                            Log.i(TAG, "【IMCORE】【QoS机制】" + pFromServer.getFp() + "已经存在于发送列表中，这是重复包，通知应用层收到该包罗! msgtype:" + pFromServer.getMsgType());
                        }

                        QoS4ReciveDaemon.getInstance().addRecieved(pFromServer);
                        this.sendRecievedBack(pFromServer);
                        return;
                    }

                    QoS4ReciveDaemon.getInstance().addRecieved(pFromServer);
                    this.sendRecievedBack(pFromServer);
                }
                if (ClientCoreSDK.DEBUG) {
                    Log.i(TAG, "【IMCORE】【QoS机制】 处理消息:消息类型" + pFromServer.getMsgType());
                }
                switch (pFromServer.getMsgType()) {
                    //IM服务器登录响应
                    case 0:
                        this.onServerResponseLogined(pFromServer);
                        break;
                    //上线通知
                    case 1:
                        this.fireOnlineNotice(pFromServer);
                        break;
                    //下线通知
                    case 2:
                        this.fireOffLineNotice(pFromServer);
                        break;
                    //收到回执
                    case 3:
                        this.onRecievedACK(pFromServer);
                        break;
                    //心跳
                    case 4:
                        this.onResponseKeepAlive();
                        break;
                    //文本消息
                    case 5:
                        this.onResponseTxt(pFromServer);
                        break;
                        //收到好友添加消息
                    case 9:
                        this.onResponseFriendAdd(pFromServer);
                        break;
                    //普通消息
                    case 20:
//                        if (ClientCoreSDK.getInstance().getChatTransDataEvent() != null) {
//                            ClientCoreSDK.getInstance().getChatTransDataEvent().onTransBuffer(
//                                    pFromServer.getFp(), pFromServer.getFid(),
//                                    pFromServer.getTxt(), pFromServer.getMsgType());
//                        }
                        break;

                }


            } catch (Exception e) {
                e.printStackTrace();
                Log.w(TAG, "【IMCORE】处理消息的过程中发生了错误.", e);
            }
        }
    }

    private void onServerResponseLogined(ImMsgBean pFromServer) {
        //登陆 重复登陆
        if (pFromServer.getSignIn() == SignInType.SUCCEED.getValue()
                || pFromServer.getSignIn() == SignInType.REPEAT.getValue()) {
            fireConnectedToServer();

            Log.i(TAG, "recallMessage IM服务器登录响应");
            if (ClientCoreSDK.getInstance().getImEvent() != null) {
                ClientCoreSDK.getInstance().getImEvent().onLoginResponse(0, pFromServer.getFp());
            }
        } else {
            LocalDataReciever.getInstance().stop();
            ClientCoreSDK.getInstance().setConnectedToServer(false);
        }
    }
    //连接到Im服务器的操作
    private void fireConnectedToServer() {
        ClientCoreSDK.getInstance().setLoginHasInit(true);
        AutoReLoginDaemon.getInstance().stop();
        KeepAliveDaemon.getInstance().setNetworkConnectionLostObserver((observable, data) -> {
            this.fireDisconnectedToServer();
        });
        KeepAliveDaemon.getInstance().start(false);
        QoS4SendDaemon.getInstance().startup(true);
        QoS4ReciveDaemon.getInstance().startup(true);
        ClientCoreSDK.getInstance().setConnectedToServer(true);
    }
    //Im服务器断开的操作
    private void fireDisconnectedToServer() {
        LocalSocketProvider.getInstance().closeLocalSocket();
        QoS4ReciveDaemon.getInstance().stop();
        ClientCoreSDK.getInstance().setConnectedToServer(false);
        if (ClientCoreSDK.getInstance().getImEvent() != null) {
            ClientCoreSDK.getInstance().getImEvent().onLinkClose(-1);
        }
        //重启重连操作
        AutoReLoginDaemon.getInstance().start(true);
    }

    //上线通知
    private void fireOnlineNotice(ImMsgBean pFromServer) {
        String uid = pFromServer.getUid();
        Log.i(TAG, "新上线的好友id:" + uid);
        if (ClientCoreSDK.getInstance().getImEvent() !=null){
            ClientCoreSDK.getInstance().getImEvent().FriendOnline(uid);
        }
    }

    //下线通知
    private void fireOffLineNotice(ImMsgBean pFromServer) {
        String uid = pFromServer.getUid();
        Log.i(TAG, "新下线的好友id:" + uid);
        if (ClientCoreSDK.getInstance().getImEvent() !=null){
            ClientCoreSDK.getInstance().getImEvent().FriendOffline(uid);
        }
    }

    //收到回执
    private void onRecievedACK(ImMsgBean pFromServer) {
        String theFingerPrint = pFromServer.getAck();
        if (ClientCoreSDK.DEBUG) {
            Log.i(TAG, "【IMCORE】【QoS】收到" + pFromServer.getFid() + "发过来的指纹为" + theFingerPrint + "的应答包.");
        }

        if (ClientCoreSDK.getInstance().getImEvent() != null &&theFingerPrint !=null) {
            ClientCoreSDK.getInstance().getImEvent().messagesReceived(theFingerPrint);
        }

        QoS4SendDaemon.getInstance().remove(theFingerPrint);
    }

    //心跳
    private void onResponseKeepAlive() {
        if (ClientCoreSDK.DEBUG) {
            Log.i(TAG, "【IMCORE】收到服务端回过来的Keep Alive心跳响应包.");
        }
        KeepAliveDaemon.getInstance().updateGetKeepAliveResponseFromServerTimstamp();
    }
    //文本消息
    private void onResponseTxt(ImMsgBean pFromServer){
        if (ClientCoreSDK.DEBUG) {
            Log.i(TAG, "处理文本消息,type:"+pFromServer.getType());
        }
        if(pFromServer.getType() == ChatType.SINGLE.getValue()){

        }else if (pFromServer.getType() == ChatType.TEMP.getValue()){

        }else {

        }

    }
    //收到好友添加消息
    private void onResponseFriendAdd(ImMsgBean pFromServer){
        if (ClientCoreSDK.DEBUG) {
            Log.i(TAG, "处理好友添加,type:"+pFromServer.getType());
        }

        if (ClientCoreSDK.getInstance().getImEvent() != null){
            ClientCoreSDK.getInstance().getImEvent().FriendAddReq(pFromServer);
        }
    }


    private void sendRecievedBack(ImMsgBean pFromServer) {//消息回执
        if (!StringUtils.isEmpty(pFromServer.getFp())) {
            (new LocalDataSender.SendCommonDataAsync(ImMsgFactory.createRecivedBack(pFromServer.getTid(), pFromServer.getFid(), pFromServer.getFp())) {
                protected void onPostExecute(Integer code) {
                    if (ClientCoreSDK.DEBUG) {
                        Log.i(TAG, "【IMCORE】【QoS】向" + pFromServer.getFid() + "发送" + pFromServer.getFp() + "包的应答包成功,from=" + pFromServer.getTid() + "！");
                    }
                }
            }).execute(new Object[0]);
        } else {
            Log.i(TAG, "【IMCORE】【QoS】收到" + pFromServer.getFid() + "发过来需要QoS的包，但它的指纹码却为空!无法发应答包!");
        }
    }


}
