package com.mogo.cloud.live.socket;

import android.content.Context;
import android.util.Log;

import com.mogo.cloud.socket.IMogoCloudSocketMsgAckListener;
import com.mogo.cloud.socket.IMogoCloudSocketOnMessageListener;
import com.mogo.cloud.socket.SocketManager;
import com.mogo.cloud.socket.entity.MsgBody;

/**
 * Socket常链接工具类
 */
public class SocketMsgUtils implements IMogoCloudSocketMsgAckListener {
    private static final String TAG = "SocketMsgUtils";

    private static final String appId = "liveStream";
    private static final int headerType = 1973;

    private static volatile SocketMsgUtils sInstance;

    private SocketManager mSocketManager;
    private final Context mContext;
    private IMogoCloudSocketOnMessageListener mMessageListener;

    public static SocketMsgUtils getInstance(Context context, IMogoCloudSocketOnMessageListener listener) {
        if (sInstance == null) {
            synchronized (SocketMsgUtils.class) {
                if (sInstance == null) {
                    sInstance = new SocketMsgUtils(context.getApplicationContext(), listener);
                }
            }
        }
        return sInstance;
    }

    private SocketMsgUtils(Context context, IMogoCloudSocketOnMessageListener listener) {
        mContext = context;
        initSocket(listener);
    }

    /**
     * 初始化长连接
     */
    private void initSocket(IMogoCloudSocketOnMessageListener listener) {
        Log.i(TAG, "初始化长连接……");
        mSocketManager = SocketManager.getInstance();
        mMessageListener = listener;
        mSocketManager.init(mContext,"",0,0);
        mSocketManager.registerOnMessageListener(401017, listener);
    }

    /**
     * 释放资源
     */
    public void release() {
        mSocketManager.release();
        mSocketManager.unregisterOnMessageListener(401017, mMessageListener);
    }

    /**
     * 上传相机信息
     *
     * @param body 数据包
     */
    public void uploadCamInfo(MsgBody body) {
        mSocketManager.sendMsg(appId, headerType, body, this);
    }

    @Override
    public void onAck(long msgId) {
        Log.i(TAG, "msgId=" + msgId);
    }
}
