package com.gamedog.vididin.widget


import android.content.Context
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.PopupWindow
import com.pierfrancescosoffritti.androidyoutubeplayer.core.customui.R
import com.pierfrancescosoffritti.androidyoutubeplayer.core.customui.menu.MenuItem
import com.pierfrancescosoffritti.androidyoutubeplayer.core.customui.menu.YouTubePlayerMenu
import kotlin.jvm.java


internal class MyPlayerMenu(private val context: Context) : YouTubePlayerMenu {
    private val menuItems = kotlin.collections.ArrayList<MenuItem>()
    private var popupWindow: PopupWindow? = null

    override val itemCount: Int
        get() = menuItems.size

    override fun show(anchorView: View) {
        popupWindow = createPopupWindow()
        popupWindow?.showAsDropDown(
            anchorView,
            -context.resources.getDimensionPixelSize(R.dimen.ayp_8dp) * 12,
            -context.resources.getDimensionPixelSize(R.dimen.ayp_8dp) * 12
        )

        if (menuItems.size == 0)
            Log.e(YouTubePlayerMenu::class.java.name, "The menu is empty")
    }

    override fun dismiss() {
        popupWindow?.dismiss()
    }

    override fun addItem(menuItem: MenuItem): YouTubePlayerMenu {
        menuItems.add(menuItem)
        return this
    }

    override fun removeItem(itemIndex: Int): YouTubePlayerMenu {
        menuItems.removeAt(itemIndex)
        return this
    }

    override fun removeItem(menuItem: MenuItem): YouTubePlayerMenu {
        menuItems.remove(menuItem)
        return this
    }

    private fun createPopupWindow(): PopupWindow {
        val view = FrameLayout(context)
        val popupWindow = PopupWindow(
            view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        popupWindow.contentView = view
        popupWindow.isFocusable = true
        popupWindow.width = WindowManager.LayoutParams.WRAP_CONTENT
        popupWindow.height = WindowManager.LayoutParams.WRAP_CONTENT

        return popupWindow
    }
}
