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.activityViewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.CloudApi
import com.doverfuelingsolutions.issp.data.DataStore
import com.doverfuelingsolutions.issp.databinding.FragmentLoginBinding
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.doverfuelingsolutions.issp.view.MainActivity
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch

class FragmentLogin : Fragment(), View.OnClickListener {

    companion object {

        const val KEY_LOGIN_RESULT = "loginResult"
    }

    private val globalViewModel: MainActivity.GlobalViewModel by activityViewModels()
    private val loginViewModel = LoginViewModel()

    private lateinit var binding: FragmentLoginBinding
    private val snackbar: Snackbar by lazy {
        Snackbar.make(binding.loginForm, "", 4000)
            .apply { anchorView = binding.loginForm }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        findNavController().previousBackStackEntry?.savedStateHandle?.set(KEY_LOGIN_RESULT, false)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false)
        binding.lifecycleOwner = this
        binding.viewModel = loginViewModel
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.buttonLogin.setOnClickListener(this)
        binding.buttonPreference.setOnClickListener(this)
        loginViewModel.accountName.value = DataStore.accountName
        loginViewModel.password.value = DataStore.password
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.buttonLogin -> submit()
            binding.buttonPreference -> findNavController().navigate(R.id.action_fragmentLogin_to_fragmentPreference)
        }
    }

    private fun submit() {
        if (loginViewModel.submitting.value == true) return

        lifecycleScope.launch {
            loginViewModel.submitting.value = true
            val accountName = loginViewModel.accountName.value?.trim()
            val password = loginViewModel.password.value?.trim()
            when {
                accountName.isNullOrBlank() || password.isNullOrBlank() -> snackbar.setText(R.string.input_not_right).show()
                else -> {
                    val result = CloudApi.login(accountName, password)
                    if (!result.success) snackbar.setText(StringUtil.get(R.string.login_fail_reason, result.message)).show()
                    else {
                        globalViewModel.isLogin.value = true
                        findNavController().previousBackStackEntry?.savedStateHandle?.set(KEY_LOGIN_RESULT, true)
                        findNavController().popBackStack()
                    }
                }
            }
            loginViewModel.submitting.value = false
        }
    }

    class LoginViewModel : ViewModel() {
        val accountName = MutableLiveData("")
        val password = MutableLiveData("")
        val submitting = MutableLiveData(false)
    }
}