package com.doverfuelingsolutions.issp.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.CloudApi
import com.doverfuelingsolutions.issp.data.GlobalData
import com.doverfuelingsolutions.issp.databinding.ActivityLoginBinding
import com.doverfuelingsolutions.issp.utils.PermissionUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity(),
    View.OnClickListener {

    private val loginViewModel: LoginViewModel by viewModels()
    private val binding: ActivityLoginBinding by lazy { DataBindingUtil.setContentView(this, R.layout.activity_login) }
    private val snackbar: Snackbar by lazy {
        Snackbar.make(binding.loginForm, "", 4000)
            .apply { anchorView = binding.loginForm }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.lifecycleOwner = this
        binding.loginViewModel = loginViewModel
        binding.buttonLogin.setOnClickListener(this)
        binding.buttonPreference.setOnClickListener(this)

        PermissionUtil.requestPermissions(this)

        if (GlobalData.isLogin) startMain()
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.buttonLogin -> submit()
            binding.buttonPreference -> PreferenceActivity.start(this)
        }
    }

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

        lifecycleScope.launch {
            loginViewModel.submitting.value = true
            val accountName = loginViewModel.accountName.value
            val password = loginViewModel.password.value
            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 {
                        GlobalData.isLogin = true
                        startMain()
                    }
                }
            }
            loginViewModel.submitting.value = false
        }
    }

    private fun startMain() {
        MainActivity.start(this@LoginActivity)
        finish()
    }

    class LoginViewModel : ViewModel() {
        val accountName = MutableLiveData(GlobalData.accountName.get())
        val password = MutableLiveData(GlobalData.password.get())
        val submitting = MutableLiveData(false)
    }
}