package com.doverfuelingsolutions.issp.view

import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.WayneApi
import com.doverfuelingsolutions.issp.data.DataStore
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.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var activityLoginBinding: ActivityLoginBinding
    private val mainViewModel = MainViewModel()

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

    private val coroutineMain = CoroutineScope(Dispatchers.Main)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityLoginBinding = DataBindingUtil.setContentView(this, R.layout.activity_login)
        activityLoginBinding.lifecycleOwner = this
        initView()
        autoLogin()

        PermissionUtil.requestPermissions(this)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (grantResults.contains(PackageManager.PERMISSION_DENIED)) {
            finish()
        }
    }

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

    private fun initView() {
        activityLoginBinding.mainViewModel = mainViewModel
        activityLoginBinding.buttonLogin.setOnClickListener(this)
        activityLoginBinding.buttonPreference.setOnClickListener(this)

        mainViewModel.accountName.value = DataStore.accountName
        mainViewModel.password.value = DataStore.password
    }

    private fun autoLogin() {
        if (DataStore.accountName.isNotEmpty() && DataStore.password.isNotEmpty()) submit()
    }

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

        coroutineMain.launch {
            mainViewModel.submitting.value = true
            val accountName = mainViewModel.accountName.value?.trim()
            val password = mainViewModel.password.value?.trim()
            when {
                accountName.isNullOrBlank() || password.isNullOrBlank() -> snackbar.setText(R.string.input_not_right).show()
                else -> {
                    val result = WayneApi.login(accountName, password)
                    if (!result.success) snackbar.setText(StringUtil.get(R.string.login_fail, result.message)).show()
                    else {
                        MainActivity.start(this@LoginActivity)
                        finish()
                        return@launch
                    }
                }
            }
            mainViewModel.submitting.value = false
        }
    }

    class MainViewModel : ViewModel() {
        val accountName = MutableLiveData<String>()
        val password = MutableLiveData<String>()
        
        val submitting = MutableLiveData<Boolean>()
    }
}