package com.xd.binddemokotlin

import android.content.Context
import android.content.Intent
import android.os.*
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider


class MainUIFragment : Fragment() {
    private lateinit var startServiceButton: Button
    private lateinit var stopServiceButton: Button
    private lateinit var bindButton: Button
    private lateinit var unbindButton: Button
    private lateinit var intValueLabel: TextView

    private lateinit var appContext: Context
    private var isBind = false
    private lateinit var myViewModel: MyViewModel
    private val BIND_STATUS_KEY = "bind_status_key"
    private lateinit var backPressedCallback: OnBackPressedCallback
    private lateinit var intent: Intent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        intent = Intent(activity, CounterService::class.java)
        appContext = requireActivity().applicationContext
        myViewModel = ViewModelProvider(requireActivity()).get(MyViewModel::class.java)
        myViewModel.counter.observe(this, Observer { it ->
            intValueLabel.text = "Int Message: $it"
        })
        if(savedInstanceState != null)
            isBind = savedInstanceState.getBoolean(BIND_STATUS_KEY)
    }

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view: View = inflater.inflate(R.layout.fragment_main_u_i, container, false)
        startServiceButton = view.findViewById(R.id.btnStart)
        stopServiceButton = view.findViewById(R.id.btnStop)
        bindButton = view.findViewById(R.id.btnBind)
        unbindButton = view.findViewById(R.id.btnUnbind)
        intValueLabel = view.findViewById(R.id.textIntValue)
        startServiceButton.setOnClickListener(){ it -> onClick(it)}
        stopServiceButton.setOnClickListener(){ it -> onClick(it)}
        bindButton.setOnClickListener(){ it -> onClick(it)}
        unbindButton.setOnClickListener(){ it -> onClick(it)}

        backPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                println("debug: back button pressed")
                unBindService()
                requireActivity().stopService(intent)
                isEnabled = false
//                activity?.onBackPressed()
                requireActivity().finish()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(requireActivity(), backPressedCallback)
        return view
    }

    override fun onDestroy() {
        super.onDestroy()
        println("debug: Fragment destroyed")
//        backPressedCallback.isEnabled = false
        backPressedCallback.remove()
    }

    fun onClick(view: View) {

        if (view == startServiceButton) {
            requireActivity().startService(intent)
        } else if (view == stopServiceButton) {
            unBindService()
            requireActivity().stopService(intent)
        } else if (view == bindButton) {
            bindService()
        } else if (view == unbindButton) {
            unBindService()
        }
    }

    private fun bindService(){
        if (!isBind) {
            appContext.bindService(intent, myViewModel, Context.BIND_AUTO_CREATE)
            isBind = true
        }
    }

    private fun unBindService(){
        if (isBind) {
            appContext.unbindService(myViewModel)
            isBind = false
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean(BIND_STATUS_KEY, isBind)
    }


}