package com.soundapp.soundgags.setting

import android.app.Activity
import android.graphics.Color
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import com.soundapp.soundgags.databinding.FragClockChooseBinding

class ClockChooseFragment(context: Activity, private val mListener: TimerThisListener) : View.OnClickListener {

    private val binding: FragClockChooseBinding = FragClockChooseBinding.inflate(context.layoutInflater)
    private val popupWindow: PopupWindow = PopupWindow(
        binding.root,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )

    init {
        popupWindow.isOutsideTouchable = true
        popupWindow.isFocusable = true
        binding.tvOff.isSelected = true
        binding.tvOff.setOnClickListener(this)
        binding.tv15s.setOnClickListener(this)
        binding.tv30s.setOnClickListener(this)
        binding.tv1m.setOnClickListener(this)
        binding.tv5m.setOnClickListener(this)
    }

    fun showTop(view: View) {
        val location = IntArray(2)
        view.getLocationOnScreen(location)

        val x = location[0]
        val y = location[1]

        val popupHeight = popupWindow.height
        val height = view.height
        val width = view.width
        Log.d("-------------", "--------x=$x---y=$y----popupHeight=$popupHeight")

        popupWindow.showAsDropDown(view, -50, 0, Gravity.NO_GRAVITY)
    }

    private fun setSelected(tv: SetTxtView) {
        val childCount = binding.layoutTime.childCount
        for (i in 0 until childCount) {
            val child = binding.layoutTime.getChildAt(i)
            if (child is SetTxtView) {
                if (child == tv) {
                    child.isSelected = true
                    child.setTextColor(Color.parseColor("#202859"))
                } else {
                    child.isSelected = false
                    child.setTextColor(Color.parseColor("#202859"))
                }
                println("TextView: ${child.text}")
            }
        }
    }

    fun hide() {
        popupWindow.dismiss()
    }

    fun setOffSelected() {
        setSelected(binding.tvOff)
    }

    override fun onClick(v: View) {
        if (v is SetTxtView) {
            val string = v.text.toString()
            when (string) {
                "off" -> mListener.onClickTimerListener(-1)
                "15 sec" -> mListener.onClickTimerListener(15 * 1000L)
                "30 sec" -> mListener.onClickTimerListener(30 * 1000L)
                "1 min" -> mListener.onClickTimerListener(60 * 1000L)
                "5 min" -> mListener.onClickTimerListener(5 * 60 * 1000L)
            }
            setSelected(v)
        }
    }
}