package com.develop.food.base.widgets

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.UiThread

abstract class SimpleViewLayer(private val context: Context) {

    private var rootView: View? = null

    abstract fun getViewLayout(): Int

    @UiThread
    fun showLayer(parent: FrameLayout) {
        if (isLayerAttach()) {
            return
        }
        setupLayer()
        removeLayer()
        parent.addView(rootView, FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        ))
    }

    @UiThread
    fun removeLayer() {
        if (isLayerAttach()) {
            val parent = rootView?.parent as ViewGroup
            parent.removeView(rootView)
        }
    }

    @UiThread
    fun isLayerAttach(): Boolean {
        return rootView != null && rootView?.parent != null
    }

    fun getView(): View? {
        return rootView
    }

    private fun setupLayer() {
        if (rootView == null) {
            rootView = View.inflate(context, getViewLayout(), null)
        }
    }
}