package com.dlc.eboard.ui

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import com.dlc.eboard.common.CommonUtils
import com.rc.httpcore.client.ApiRepository
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable

/**
 * info
 *
 * @author ReiChin_
 */
class HeartService : Service(), Runnable {

    private val mHandler = Handler()

    override fun onCreate() {
        super.onCreate()

        mHandler.removeCallbacks(this)
        mHandler.postDelayed(this, 2000)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        clearDisposable()
        mHandler.removeCallbacks(this)
        super.onDestroy()
    }

    /**
     * 发送心跳
     */
    override fun run() {
        val disposable = ApiRepository.heartbeat(CommonUtils.getAndroidId())
            .subscribe({
                mHandler.postDelayed(this, 30000)
            }, {
                mHandler.postDelayed(this, 30000)
            })
        addDisposable(disposable)
    }

    private var mCompositeDisposable: CompositeDisposable? = null

    private fun addDisposable(disposable: Disposable) {
        mCompositeDisposable = (mCompositeDisposable ?: CompositeDisposable()).apply {
            if (!isDisposed) add(disposable)
        }
    }

    private fun clearDisposable() {
        mCompositeDisposable = mCompositeDisposable?.let {
            it.clear()
            null
        }
    }

}