package com.mogo.telematic

import android.os.Handler
import android.os.HandlerThread
import android.os.Message

object TelematicHandler {

    private const val MSG_DELAY = 100
    private const val MSG_RECONNECT_DELAY = 101

    private val handlerThread by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        HandlerThread("TelematicHandler")
    }

    private var handler: Handler? = null
    private var listener: ITelematicListener? = null

    @JvmStatic
    fun init() {
        handlerThread.start()
        handler = object : Handler(handlerThread.looper) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when (msg.what) {
                    MSG_DELAY -> {
                        listener?.delayCompleted()
                    }
                    MSG_RECONNECT_DELAY -> {
                        listener?.reconnectServer()
                    }
                }
            }
        }
    }

    @JvmStatic
    fun setListener(listener: ITelematicListener) {
        this.listener = listener
    }

    @JvmStatic
    fun delay(delayMillis: Long) {
        handler?.sendEmptyMessageDelayed(MSG_DELAY, delayMillis)
    }

    @JvmStatic
    fun delayReConnect(delayMillis: Long) {
        removeReconnect()
        handler?.sendEmptyMessageDelayed(MSG_RECONNECT_DELAY, delayMillis)
    }

    @JvmStatic
    fun removeDelay() {
        handler?.removeMessages(MSG_DELAY)
    }

    @JvmStatic
    fun removeReconnect() {
        handler?.removeMessages(MSG_RECONNECT_DELAY)
    }

    interface ITelematicListener {
        fun delayCompleted()

        fun reconnectServer()
    }
}