package cn.yyxx.eyuangame.core.impl.floatball

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.eyuangame.base.utils.Logger
import cn.yyxx.eyuangame.core.entity.SdkBackLoginInfo
import cn.yyxx.eyuangame.core.impl.SdkBridgeImpl

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

    private var mService: FloatCenterService? = null
    private var mActivity: Activity? = null
    private var mIntent: Intent? = null
    private var isBindService = false

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mService = (service as FloatCenterService.FloatCenterServiceBinder).service
            mService?.initService(mActivity!!)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    fun init(activity: Activity) {
        this.mActivity = activity
        if (mService == null) {
            mIntent = Intent(activity.applicationContext, FloatCenterService::class.java)
            activity.applicationContext.startService(mIntent)
            activity.applicationContext.bindService(mIntent, serviceConnection, Context.BIND_AUTO_CREATE)
            isBindService = true
        }
    }

    fun attach() {
        if (mService == null) {
            Logger.e("浮标服务未初始化或发生异常")
            return
        }
        if (!TextUtils.isEmpty(SdkBackLoginInfo.instance.userId) && SdkBridgeImpl.initBean.floatCfg.switch == 1) {
            mService?.attach()
        } else {
            detach()
        }
    }

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

    fun release() {
        mService?.apply {
            release()
            if (isBindService) {
                mActivity?.applicationContext?.unbindService(serviceConnection)
                mActivity?.applicationContext?.stopService(mIntent)
            }
        }
        mIntent = null
        mActivity = null
    }


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