package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.databinding.FragmentActionBinding
import com.doverfuelingsolutions.issp.utils.StringUtil

class FragmentAction private constructor(
    private val tip: String,
    private val buttonText: String,
    private val handler: () -> Unit,
) : Fragment(), View.OnClickListener {

    companion object {

        fun build(msg: String, buttonText: String, handler: () -> Unit): FragmentAction {
            return FragmentAction(msg, buttonText, handler)
        }
    }

    private lateinit var binding: FragmentActionBinding
    private val viewModel: ActionViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (!this::binding.isInitialized) {
            binding = DataBindingUtil.inflate(inflater, R.layout.fragment_action, container, false)
            binding.lifecycleOwner = viewLifecycleOwner
            binding.viewModel = viewModel
            viewModel.actionText.value = tip
            viewModel.actionButtonText.value = buttonText
            binding.actionButton.setOnClickListener { handler.invoke() }
        }
        return binding.root
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.actionButton -> {
                handler.invoke()
            }
        }
    }

    class ActionViewModel : ViewModel() {
        val actionText = MutableLiveData(StringUtil.get(R.string.connect_timeout))
        val actionButtonText = MutableLiveData(StringUtil.get(R.string.go_check_fusion))
    }
}