package com.grkj.iscs.util

import android.content.Context
import cn.zhxu.okhttps.OkHttps
import cn.zhxu.stomp.Header
import cn.zhxu.stomp.Stomp
import com.grkj.iscs.extentions.addNetObserver
import com.grkj.iscs.extentions.removeNetObserver
import com.grkj.iscs.model.Constants
import com.grkj.iscs.model.UrlConsts
import com.grkj.iscs.util.log.LogUtil

object StompApi {

    fun refuseStomp(ctx: Context, callback: (stomp: Stomp, baseDestination: String) -> Unit) {
        stomp(ctx, "", callback)
    }


    private fun stomp(ctx: Context, destinationInfix: String, callback: (stomp: Stomp, baseDestination: String) -> Unit) {
        Executor.runOnMain {
            ctx.addNetObserver(object : OnceNetObserver() {
                override fun onNetAvailable() {
                    onNetAvailable(ctx, destinationInfix, callback)
                    ctx.removeNetObserver(this)
                }
            })
        }
    }

    private fun onNetAvailable(ctx: Context, destinationInfix: String, callback: (stomp: Stomp, baseDestination: String) -> Unit) {
//        PlatformRepository(ctx).getPlatformId().observeForever { platformId ->
//            if (platformId != null) {
//                Authorization.requestToken(ctx) { token ->
//                    if (token != null) {
//                        connectStompServer(ctx, vhost, destinationInfix, platformId, token, callback)
//                    }
//                }
//            } else {
//                LogUtil.w("platformId = null")
//            }
//        }
        connectStompServer(ctx, destinationInfix, callback)
    }

    private fun connectStompServer(ctx: Context, destinationInfix: String, callback: (stomp: Stomp, baseDestination: String) -> Unit) {
        LogUtil.i("开始连接 STOMP 服务")
//        Stomp.over(OkHttps.webSocket(Constants.WEB_SOCKET).heatbeat(20, 20))
        Stomp.over(OkHttps.webSocket(UrlConsts.WEB_SOCKET))
            .setOnConnected {
                callback(it, "/p--a.${destinationInfix}")
            }
            .setOnDisconnected {
                if (it.code != 1000) {
                    LogUtil.i("Websockt 已断开：${it.code}: ${it.reason}，10 秒后重连...")
                    Executor.delayOnIO({
                        stomp(ctx, destinationInfix, callback)
                    }, 10000)
                }
            }
            .connect()
//            .connect(listOf(
//                Header("login", token),
//                Header("host", vhost)
//            ))
    }


}