package com.sinch.android.rtc.sample.hmspush

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.sinch.android.rtc.SinchError
import com.sinch.android.rtc.sample.hmspush.PersistedHmsRegistration.setHmsApplicationId
import com.sinch.android.rtc.sample.hmspush.PersistedHmsRegistration.setHmsToken
import com.sinch.android.rtc.sample.hmspush.hms.RegisterToHmsTask

class LoginActivity : BaseActivity(), RegisterToHmsTask.RegistrationCallback {

    private lateinit var loginButton: Button
    private lateinit var loginNameEditText: EditText

    private var progressSpinner: ProgressDialog? = null
    private var hmsDeviceToken: String? = null
    private var hmsApplicationId: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login)
        loginNameEditText = findViewById(R.id.loginName)
        loginButton = findViewById(R.id.loginButton)

        loginNameEditText.setOnEditorActionListener { _: TextView?, actionId: Int, _: KeyEvent? ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                loginClicked()
                return@setOnEditorActionListener true
            }
            false
        }
        loginButton.apply {
            isEnabled = false
            setOnClickListener { loginClicked() }
        }
    }

    override fun onResume() {
        super.onResume()
        if (hmsDeviceToken?.isNotEmpty() == true) {
            loginButton.isEnabled = true
            loginButton.visibility = View.VISIBLE
        } else {
            // Huawei recommends reacquiring the Device Token each app start.
            // For simplicity of UI handling we demonstrate it here.
            loginButton.visibility = View.INVISIBLE
            RegisterToHmsTask(applicationContext, this).execute()
        }
        attachOnStartedListener()
    }

    override fun onServiceConnected() {
        attachOnStartedListener()
        if (sinchServiceInterface?.isStarted == true) {
            Toast.makeText(
                this, getString(R.string.logged_in_automatically, sinchServiceInterface?.username), Toast
                    .LENGTH_LONG
            ).show()
            openPlaceCallActivity()
        }
    }

    override fun onPause() {
        super.onPause()
        dismissSpinner()
        sinchServiceInterface?.removeOnSinchClientStartedCallback()
    }

    override fun onSinchClientFailed(error: SinchError) {
        super.onSinchClientFailed(error)
        dismissSpinner()
    }

    private fun startClientAndOpenPlaceCallActivity() {
        // Start Sinch Client, it'll result OnSinchClientStartedCallback being invoked from where the place call
        // activity will be started.
        if (sinchServiceInterface?.isStarted == false) {
            sinchServiceInterface?.startClient()
            showSpinner()
        }
    }

    private fun loginClicked() {
        val username = loginNameEditText.text.toString()
        sinchServiceInterface?.username = username
        if (username.isEmpty()) {
            Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show()
            return
        }
        startClientAndOpenPlaceCallActivity()
    }

    private fun attachOnStartedListener() {
        sinchServiceInterface?.setOnSinchClientStartedCallback {
            openPlaceCallActivity()
        }
    }

    private fun openPlaceCallActivity() {
        startActivity(Intent(this, PlaceCallActivity::class.java))
    }

    private fun showSpinner() {
        progressSpinner = ProgressDialog(this).apply {
            setTitle("Logging in")
            setMessage("Please wait...")
            show()
        }
    }

    private fun dismissSpinner() {
        progressSpinner?.dismiss()
    }

    override fun onRegisterComplete(deviceToken: String?, applicationId: String?) {
        hmsDeviceToken = deviceToken
        hmsApplicationId = applicationId
        if (hmsDeviceToken == null || hmsApplicationId?.isEmpty() == true) {
            Toast.makeText(
                this, "Failed to get HMS Device Token. Make sure that the app is signed and the "
                        + "signature's fingerprint is uploaded to the Huawei AppGallery console.",
                Toast.LENGTH_LONG
            ).show()
            loginButton.isEnabled = false
            return
        } else {
            // Store HMS registration data to use it when creating SinchClient.
            setHmsToken(applicationContext, hmsDeviceToken)
            setHmsApplicationId(
                applicationContext,
                hmsApplicationId
            )
            loginButton.visibility = View.VISIBLE
            loginButton.isEnabled = true
        }
    }

    companion object {
        private val TAG = LoginActivity::class.java.simpleName
    }
}
