package com.adealink.weparty.commonui.widget.floatview.view

import android.app.Activity
import android.view.View
import androidx.annotation.CallSuper
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.adealink.frame.util.AppUtil
import com.adealink.weparty.commonui.widget.floatview.BaseWindowManager
import com.adealink.weparty.commonui.widget.floatview.data.IFloatData

abstract class BaseFloatView<DATA : IFloatData>(var baseFloatData: DATA) :
    ConstraintLayout(AppUtil.appContext),
    LifecycleOwner,
    ViewModelStoreOwner {

    protected var windowManager: BaseWindowManager? = null
    override val viewModelStore = ViewModelStore()
    private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
    override val lifecycle: Lifecycle
        get() = lifecycleRegistry

    var onSelfRemovedCallback: (() -> Unit)? = null

    init {
        lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED
    }

    fun setContentView(view: View, layoutParams: LayoutParams? = null) {
        addView(
            view,
            layoutParams ?: LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
                startToStart = LayoutParams.PARENT_ID
                endToEnd = LayoutParams.PARENT_ID
                topToTop = LayoutParams.PARENT_ID
                bottomToBottom = LayoutParams.PARENT_ID
            }
        )
    }

    @CallSuper
    open fun onCreate() {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
    }

    @CallSuper
    open fun onStart() {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    @CallSuper
    open fun onResume() {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
    }

    @CallSuper
    open fun onPause() {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    }

    @CallSuper
    open fun onStop() {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }

    @CallSuper
    open fun onDestroy() {
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        viewModelStore.clear()
    }

    @CallSuper
    open fun onSaveInstance() {
        lifecycleRegistry.currentState = Lifecycle.State.CREATED
    }

    @CallSuper
    open fun updateInfo(baseFloatData: DATA) {
        this.baseFloatData = baseFloatData
    }

    fun setupWindowManager(windowManager: BaseWindowManager) {
        this.windowManager = windowManager
    }

    open fun removeSelf(reason: String) {
        windowManager?.removeView(this, reason)
        onSelfRemovedCallback?.invoke()
    }

    open fun onActivityChange(activity: Activity) {}

    open fun onEnterBackground() {}

    open fun onEnterForeground() {}

}