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

import android.view.ViewGroup
import android.view.WindowManager
import com.adealink.frame.log.Log
import com.adealink.weparty.commonui.widget.floatview.data.FloatWindowType
import com.adealink.weparty.commonui.widget.floatview.data.TAG_FLOAT_VIEW
import com.adealink.weparty.commonui.widget.floatview.view.BaseLayoutFloatView
import com.adealink.weparty.commonui.widget.floatview.view.IFloatViewGroup

class LayoutViewContainer(
    val layoutView: IFloatViewGroup<BaseLayoutFloatView>, //容器控件
    val windowLayoutParams: WindowManager.LayoutParams,
) : IViewManager<BaseLayoutFloatView> {
    companion object {
        private const val SUB_TAG = "LayoutViewContainer"
    }

    fun view(): ViewGroup {
        return layoutView.viewGroup()
    }

    fun childCount(): Int {
        return layoutView.viewGroup().childCount
    }

    fun onResume(layoutDirection: Int) {
        if (windowLayoutParams.token != null) {
            layoutView.onResume(layoutDirection)
        }
    }

    fun onPause() {
        if (windowLayoutParams.token != null) {
            layoutView.onPause()
        }
    }

    override fun addView(wm: WindowManager, view: BaseLayoutFloatView) {
        if (view.parent != null) {
            (view.parent as ViewGroup).removeView(view)
        }
        try {
            layoutView.addFloatView(view)
        } catch (e: Exception) {
            //添加视图失败
            Log.e(TAG_FLOAT_VIEW, "addView fail, for ${e.message}")
        }
    }

    override fun removeView(wm: WindowManager, view: BaseLayoutFloatView, reason: String) {
        try {
            if (!layoutView.containsView(view)) {
                Log.w(TAG_FLOAT_VIEW, "$SUB_TAG, removeView return, view not add")
                return
            }
            if (layoutView.viewGroup().childCount <= 1) {
                Log.i(TAG_FLOAT_VIEW, "$SUB_TAG, removeView layoutView.viewGroup().childCount <= 1")
                if (windowLayoutParams.token != null) {
                    wm.removeView(layoutView.viewGroup())
                    windowLayoutParams.token = null
                } else {
                    Log.i(
                        TAG_FLOAT_VIEW,
                        "$SUB_TAG, removeView return for windowLayoutParams.token is null"
                    )
                }
            }
            layoutView.removeFloatView(view)
        } catch (e: Exception) {
            //移除视图失败
            Log.e(TAG_FLOAT_VIEW, "removeView fail, for ${e.message}")
        }
    }

    override fun findFloatViewByType(type: FloatWindowType): BaseLayoutFloatView? {
        return layoutView.findFloatViewByType(type)
    }
}