package com.grkj.iscs_mc.util

import androidx.lifecycle.MutableLiveData
import cn.zhxu.okhttps.OkHttps
import cn.zhxu.stomp.Header
import cn.zhxu.stomp.Stomp
import com.grkj.iscs_mc.model.Constants
import com.grkj.iscs_mc.model.UrlConsts
import com.grkj.iscs_mc.util.log.LogUtil
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

class StompManager {
    var myStomp: Stomp?=null
    var scheduledExecutorService:ScheduledExecutorService?=null
    var cacheTime=0L
    var cacheDisconnectTime=0L
    var topicRefuseStr:String?=null
    val serverData = MutableLiveData<String>()

    companion object{
        fun getInstance() = InstanceHelper.sSingle
    }

    object InstanceHelper{
        val sSingle = StompManager()
    }

    fun startStomp(){
        if (myStomp?.isConnected==true){return}
        LogUtil.d("stomp连接开始!")
        NetHttpManager.getInstance().requestTokenAndRefreshIfExpired {
            if (!it.isNullOrBlank()){
                myStomp=Stomp.over(OkHttps.webSocket(UrlConsts.WEB_SOCKET).heatbeat(10,10))
                    .setOnConnected {
                        scheduledExecutorService?.shutdownNow()
                        scheduledExecutorService=null
                        LogUtil.d("stomp连接完成!")
                        cacheTime=System.currentTimeMillis()
                        if (cacheDisconnectTime>20*1000){
//                            NetStateUtil.instance.setNetState(0)
                        }
                        topicRefuse()
                    }
                    .setOnDisconnected {
                        LogUtil.d("stomp连接断开：${it.reason}")
                        cacheDisconnectTime=System.currentTimeMillis()-cacheTime
//                        NetStateUtil.instance.setNetState(2)
                        reConnectStomp()
                    }
                    .setOnException {
                        LogUtil.d("stomp连接异常：${it.toString()}")
                        cacheDisconnectTime=System.currentTimeMillis()-cacheTime
//                        NetStateUtil.instance.setNetState(2)
                        reConnectStomp()
                    }
                    .setOnError {
                        LogUtil.d("stomp连接错误：${it.toString()}")
                        cacheDisconnectTime=System.currentTimeMillis()-cacheTime
//                        NetStateUtil.instance.setNetState(2)
                        reConnectStomp()
                    }
                    .connect(listOf(Header("login",it),Header("host","/eiotyun-kitchen-refuse")))
            }else{
                reConnectStomp()
            }
        }
    }

    fun topicRefuse(){
//        FenBiDeNetApi.getInstance().getPlatformInfo {
//            it?.let {
//                topicRefuseStr?.let {
//                    myStomp?.untopic(it)
//                }
//                topicRefuseStr="/p-${it.platformId}-a.machine.${AppUtils.getSerialNo(FenBiDeApplication.instance)}"
//                //创建设备
//                myStomp?.topic(topicRefuseStr){
//                    EventBus.getDefault().post(StompCreatEvent(it.payload=="1",it.payload))
//                }
//                //配置参数
//                myStomp?.topic("${topicRefuseStr}.refresh"){
//                    try {
//                        EventBus.getDefault().post(Gson().fromJson(it.payload, StompRefreshEvent::class.java))
//                    }catch (e:Exception){
//                        ToastUtils.tip(FenBiDeApplication.instance.getString(R.string.str_stomp_exception,it.payload))
//                        LogUtil.d("refresh：${FenBiDeApplication.instance.getString(R.string.str_stomp_exception,it.payload)}",e)
//                    }
//                }
//            }?:let {
//                try {
//                    Thread.sleep(10000)
//                }catch (e:Exception){}
//                topicRefuse()
//            }
//        }
    }

    fun stopStomp(){
        topicRefuseStr?.let {
            myStomp?.untopic(it)
        }
        myStomp?.disconnect(true)
    }

    fun reConnectStomp(){
        scheduledExecutorService?:let {
            scheduledExecutorService= Executors.newScheduledThreadPool(1)
            scheduledExecutorService?.scheduleWithFixedDelay(Runnable {
                startStomp()
            },0,30000, TimeUnit.MILLISECONDS)
        }
    }

}