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

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

class PlaceCallActivity : BaseActivity() {

    private lateinit var callButton: Button
    private lateinit var logoutButton: Button
    private lateinit var calleeNameEditText: EditText
    private lateinit var loggedInNameTextView: TextView

    private val buttonClickListener = View.OnClickListener { v ->
        when (v.id) {
            R.id.callButton -> callButtonClicked()
            R.id.logoutButton -> logoutButtonClicked()
            else -> {}
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)
        calleeNameEditText = findViewById(R.id.callName)
        callButton = findViewById(R.id.callButton)
        logoutButton = findViewById(R.id.logoutButton)
        loggedInNameTextView = findViewById(R.id.loggedInName)

        calleeNameEditText.setOnEditorActionListener { _: TextView?, actionId: Int, _: KeyEvent? ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                callButtonClicked()
                return@setOnEditorActionListener true
            }
            false
        }
        callButton.apply {
            isEnabled = false
            setOnClickListener(buttonClickListener)
        }
        logoutButton.setOnClickListener(buttonClickListener)
    }

    override fun onServiceConnected() {
        loggedInNameTextView.text = sinchServiceInterface?.username.orEmpty()
        callButton.isEnabled = true
    }

    private fun logoutButtonClicked() {
        sinchServiceInterface?.unregisterPushToken()
        sinchServiceInterface?.stopClient()
        finish()
    }

    private fun callButtonClicked() {
        val userName = calleeNameEditText.text.toString()
        if (userName.isEmpty()) {
            Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show()
            return
        }
        val call = sinchServiceInterface?.callUser(userName)
        val callId = call?.callId
        val callScreen = Intent(this, CallScreenActivity::class.java)
        callScreen.putExtra(SinchService.CALL_ID, callId)
        startActivity(callScreen)
    }

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