package com.mogo.realtime.core;

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

import static com.mogo.realtime.constant.RealTimeConstant.TAG;

import androidx.annotation.Keep;



/**
 * AI云 实时上报数据频率处理类
 */
public class UploadInTimeHandler {

    private static final int MSG_DATA_CHANGED = 0x100;
    private static final long MSG_DATA_INTERNAL = 1000L;
    private final long uploadDelay = MSG_DATA_INTERNAL;

    private volatile HandlerThread mThread;
    private volatile Handler mHandler;
    private static volatile UploadInTimeHandler uploadInTimeHandler;

    private IUploadInTimeListener iUploadInTimeListener;

    private UploadInTimeHandler() {

    }

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

    public synchronized void start() {
        Log.d(TAG, "UploadInTimeHandler start");
        if (mHandler == null) {
            if (mThread == null) {
                mThread = new HandlerThread(TAG);
                Log.d(TAG, "start Handler Thread");
                mThread.start();
            }
            mHandler = new Handler(mThread.getLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == MSG_DATA_CHANGED) {
                        mHandler.sendEmptyMessageDelayed(MSG_DATA_CHANGED, uploadDelay);
                        if (iUploadInTimeListener != null) {
                            iUploadInTimeListener.sendLocationData();
                        }
                    }
                }
            };
            mHandler.sendEmptyMessage(MSG_DATA_CHANGED);
        }
    }

    public void setUploadInTimeListener(IUploadInTimeListener uploadInTimeListener) {
        this.iUploadInTimeListener = uploadInTimeListener;
    }

    public synchronized void stop() {
        if (mHandler != null) {
            mHandler.removeMessages(MSG_DATA_CHANGED);
            mHandler = null;
        }
        if (mThread != null) {
            try {
                mThread.quit();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mThread = null;
            Log.d(TAG, "stop Thread set null");
        }
        iUploadInTimeListener = null;
        uploadInTimeHandler = null;
    }

    /**
     * 实时上报数据回调
     */
    @Keep
    public interface IUploadInTimeListener {

        /**
         * 上报自车数据
         */
        @Keep
        void sendLocationData();
    }

}
