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

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?.stopClient()
        finish()
    }

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