package com.sinch.android.rtc.sample.video.push

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.tasks.Task
import com.google.firebase.messaging.FirebaseMessaging
import com.sinch.android.rtc.SinchError
import com.sinch.android.rtc.sample.video.push.FcmTokenPersistence.setFcmRegistrationToken

class LoginActivity : BaseActivity() {

    private lateinit var loginButton: Button
    private lateinit var loginNameEditText: EditText
    private var progressSpinner: ProgressDialog? = 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() }
        }
        acquireFcmRegistrationToken()
    }

    override fun onResume() {
        super.onResume()
        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 acquireFcmRegistrationToken() {
        FirebaseMessaging.getInstance().token.addOnCompleteListener { task: Task<String?> ->
            if (task.isSuccessful) {
                loginButton.isEnabled = true
                setFcmRegistrationToken(this, task.result)
            } else {
                Toast.makeText(this, "Couldn't acquire FCM registration token", Toast.LENGTH_LONG)
                    .show()
                Log.e(TAG, "Error while getting FCM registration token", task.exception)
            }
        }
    }

    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()
    }

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