package partisan.weforge.xyz.pulse

import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.button.MaterialButton
import nl.dionsegijn.konfetti.core.Party
import nl.dionsegijn.konfetti.core.Position
import nl.dionsegijn.konfetti.core.emitter.Emitter
import nl.dionsegijn.konfetti.xml.KonfettiView
import java.util.concurrent.TimeUnit

class MainFragment : Fragment() {

    private lateinit var prefs: Preferences
    private var lastConfettiTime = 0L

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_main, container, false)
        prefs = Preferences(requireContext())

        val toggle = view.findViewById<MaterialButton>(R.id.toggle)
        val konfetti = view.findViewById<KonfettiView>(R.id.confettiView)

        toggle.isCheckable = true
        toggle.isChecked = prefs.isServiceEnabledByUser

        toggle.setOnClickListener {
            // the button toggles itself internally since it's checkable
            val isNowChecked = toggle.isChecked
            prefs.isServiceEnabledByUser = isNowChecked

            if (isNowChecked && SystemClock.elapsedRealtime() - lastConfettiTime > 500) {
                konfetti.start(
                    Party(
                        emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).perSecond(100),
                        speed = 30f,
                        maxSpeed = 40f,
                        damping = 0.85f,
                        spread = 360,
                        position = Position.Relative(0.5, 0.5)
                    )
                )
                lastConfettiTime = SystemClock.elapsedRealtime()
            }

            toggle.post {
                toggle.jumpDrawablesToCurrentState()
                toggle.invalidate()
            }
        }

        return view
    }
}
