package com.mogo.realtime.core;


import static com.mogo.cloud.passport.MoGoAiCloudClientConfig.HTTP_DNS_ENV_DEMO;

import android.content.Context;

import com.mogo.cloud.passport.MoGoAiCloudClient;
import com.mogo.cloud.socket.entity.MsgBody;
import com.mogo.realtime.constant.RealTimeConstant;
import com.mogo.realtime.entity.SocketReceiveDataProto3;
import com.mogo.realtime.socket.SocketHandler;
import com.mogo.realtime.spi.RealTimeProviderImp;


/**
 * 上报坐标服务
 */
public class SnapshotUploadInTime implements UploadInTimeHandler.IUploadInTimeListener {

    private static volatile SnapshotUploadInTime sInstance;

    private SnapshotUploadInTime() {
    }

    public static SnapshotUploadInTime getInstance() {
        if (sInstance == null) {
            synchronized (SnapshotUploadInTime.class) {
                if (sInstance == null) {
                    sInstance = new SnapshotUploadInTime();
                }
            }
        }
        return sInstance;
    }

    /**
     * 开始实时定位数据上报
     *
     * @param context 上下文对象
     * @param appId   注册id
     */
    public void start(Context context, String appId) {
        //开启长链服务
        SocketHandler.getInstance().initSocket(context, appId, 0, 0);
        //上传数据服务启动，定时上报
        UploadInTimeHandler.getInstance().start();
        UploadInTimeHandler.getInstance().setUploadInTimeListener(this);
    }

    /**
     * 停止实时定位数据上报
     */
    public void stop() {
        //上传数据服务关闭
        UploadInTimeHandler.getInstance().stop();
        //关闭长链服务
        SocketHandler.getInstance().stop();
        sInstance = null;
    }

    @Override
    public void sendLocationData() {
        SocketReceiveDataProto3.SocketReceiveDataProto socketReceiveDataProto =
                RealTimeProviderImp.getInstance().getLocationMsg();//SPI接口返回
        if (socketReceiveDataProto != null) {
            MsgBody msgBody = new MsgBody();
            msgBody.msgType(getMsgType());
            msgBody.content(socketReceiveDataProto.toByteArray());
            SocketHandler.getInstance().sendMsg(msgBody);
        }
    }

    private int getMsgType() {
        if (MoGoAiCloudClient.getInstance().getAiCloudClientConfig().getNetMode() == HTTP_DNS_ENV_DEMO) {
            return RealTimeConstant.DEMO_FREQUENCY_CHANNEL_ID;
        } else {
            return RealTimeConstant.LOW_FREQUENCY_CHANNEL_ID;
        }
    }
}
