package uz.myid.sdk.sample

import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import uz.myid.android.sdk.capture.MyIdClient
import uz.myid.android.sdk.capture.MyIdConfig
import uz.myid.android.sdk.capture.MyIdException
import uz.myid.android.sdk.capture.MyIdResult
import uz.myid.android.sdk.capture.MyIdResultListener
import uz.myid.android.sdk.capture.model.MyIdBuildMode
import uz.myid.android.sdk.capture.model.MyIdGraphicFieldType
import uz.myid.android.sdk.capture.takeUserResult
import uz.myid.sdk.sample.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity(), MyIdResultListener {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    private val client = MyIdClient()

    private var buildMode = MyIdBuildMode.PRODUCTION

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            radioGroupBuildMode.setOnCheckedChangeListener { _, checkedId ->
                buildMode = if (checkedId == R.id.radioProd) {
                    MyIdBuildMode.PRODUCTION
                } else {
                    MyIdBuildMode.DEBUG
                }
            }

            buttonStart.setOnClickListener { startMyId() }
        }
    }

    override fun onSuccess(result: MyIdResult) {
        val bitmap = result.getGraphicFieldImageByType(MyIdGraphicFieldType.FACE_PORTRAIT)

        with(binding) {
            imageResult.setImageBitmap(bitmap)

            """
                Result code: ${result.code}
                Comparison value: ${result.comparison}
            """.trimIndent().also { textResult.text = it }
        }
    }

    override fun onError(e: MyIdException) {
        with(binding) {
            imageResult.setImageBitmap(null)

            """
                Result error: ${e.message}
                Result error code: ${e.code}
            """.trimIndent().also { textResult.text = it }
        }
    }

    override fun onUserExited() {
        with(binding) {
            imageResult.setImageBitmap(null)

            "User exited sdk".also { textResult.text = it }
        }
    }

    private fun startMyId() {
        val config = MyIdConfig.builder(binding.inputClientId.value)
            .withClientHash(
                clientHash = binding.inputClientHash.value,
                clientHashId = binding.inputClientHashId.value,
            )
            .withPassportData(binding.inputPassportData.value)
            .withBirthDate(binding.inputDate.value)
            .withBuildMode(buildMode)
            .build()

        val intent = client.createIntent(this, config)
        result.launch(intent)
    }

    private val result = takeUserResult(this)

    private inline val EditText.value: String get() = text.toString().trim()
}