package cn.yyxx.eyuancomm.impl.channel.huawei.floatview

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.text.TextUtils
import cn.yyxx.eyuancomm.comm.entity.SdkLoginInfo
import cn.yyxx.eyuancomm.comm.utils.Logger

/**
 * @author #Suyghur.
 * Created on 2021/06/28
 */
class FloatCenterServiceManager private constructor() {

    private var service: FloatCenterService? = null
    private var activity: Activity? = null
    private var intent: Intent? = null
    private var callback: FloatBall.FloatBallCallback? = null
    private var isBindService = false

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            this@FloatCenterServiceManager.service = (service as FloatCenterService.FloatCenterServiceBinder).service
            this@FloatCenterServiceManager.service?.initService(activity!!, callback!!)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    fun init(activity: Activity, callback: FloatBall.FloatBallCallback) {
        this.activity = activity
        this.callback = callback
        if (service == null) {
            intent = Intent(activity.applicationContext, FloatCenterService::class.java)
            activity.applicationContext.startService(intent)
            activity.applicationContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
            isBindService = true
        }
    }

    fun attach() {
        if (service == null) {
            Logger.e("浮标服务未初始化或发生异常")
            return
        }
        service?.attach()
        if (!TextUtils.isEmpty(SdkLoginInfo.instance.userId)) {
            service?.attach()
        } else {
            detach()
        }
    }

    fun detach() {
        service?.detach()
    }

    fun release() {
        service?.apply {
            release()
            if (isBindService) {
                activity?.applicationContext?.unbindService(serviceConnection)
                activity?.applicationContext?.stopService(intent)
            }
        }
        intent = null
        activity = null
        callback = null
    }


    companion object {
        val instance: FloatCenterServiceManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            FloatCenterServiceManager()
        }
    }
}