package com.sinch.android.rtc.sample.pstn

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
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.sinch.android.rtc.SinchError

class LoginActivity : BaseActivity(), SinchService.StartFailedListener {

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

    override fun onServiceConnected() {
        loginButton.isEnabled = true
        sinchServiceInterface?.setStartListener(this)
    }

    override fun onPause() {
        progressSpinner?.dismiss()
        super.onPause()
    }

    override fun onFailed(error: SinchError) {
        Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show()
        progressSpinner?.dismiss()
    }

    override fun onStarted() {
        openPlaceCallActivity()
    }

    private fun loginClicked() {
        val sinchServiceInterface = sinchServiceInterface ?: return
        val username = loginNameEditText.text.toString()
        if (username.isEmpty()) {
            Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show()
            return
        }
        if (username != sinchServiceInterface.userName) {
            sinchServiceInterface?.stopClient()
        }
        if (!sinchServiceInterface.isStarted) {
            sinchServiceInterface.startClient(username)
            showSpinner()
        } else {
            openPlaceCallActivity()
        }
    }

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

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