package invalid.lena.rsend

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlin.concurrent.thread

// RemoteActivity edits the SSH target and runs Test connection, which scans the
// host key and pins it on the user's confirmation.
class RemoteActivity : AppCompatActivity() {

    private lateinit var host: EditText
    private lateinit var port: EditText
    private lateinit var user: EditText
    private lateinit var status: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_remote)
        setSupportActionBar(findViewById(R.id.toolbar))
        title = "Remote"
        fitSystemBars()
        host = findViewById(R.id.host)
        port = findViewById(R.id.port)
        user = findViewById(R.id.user)
        status = findViewById(R.id.status)

        val cfg = Config.load(this)
        host.setText(cfg.remote.host)
        port.setText(cfg.remote.port.toString())
        user.setText(cfg.remote.user)

        findViewById<Button>(R.id.save).setOnClickListener { if (save()) finish() }
        findViewById<Button>(R.id.test).setOnClickListener { test() }
    }

    private fun current(): Remote? {
        val p = port.text.toString().toIntOrNull()
        if (p == null || p !in 1..65535) {
            status.text = "Port must be between 1 and 65535."
            return null
        }
        return Remote(
            host = host.text.toString().trim(),
            port = p,
            user = user.text.toString().trim(),
        )
    }

    private fun save(remote: Remote? = current()): Boolean {
        if (remote == null) return false
        val cfg = Config.load(this)
        if (cfg.remote.host != remote.host || cfg.remote.port != remote.port) Keys.clearPin(this)
        Config.save(this, cfg.copy(remote = remote))
        return true
    }

    private fun test() {
        val r = current() ?: return
        save(r)
        when {
            !Keys.exists(this) ->
                status.text = "No key yet. Generate one on the main screen and add it to the server first."
            r.host.isEmpty() || r.user.isEmpty() ->
                status.text = "Set host and user first."
            else -> {
                status.text = "Connecting to ${r.user}@${r.host}:${r.port} ..."
                thread {
                    val scan = try {
                        Keys.scan(this, r)
                    } catch (e: Exception) {
                        Keys.Scan(false, "", "", e.message ?: "connection failed")
                    }
                    runOnUiThread {
                        if (isFinishing || isDestroyed) return@runOnUiThread
                        if (!scan.ok) {
                            status.text = "Connection failed:\n${scan.error}"
                        } else {
                            AlertDialog.Builder(this)
                                .setTitle("Verify host key")
                                .setMessage("Fingerprint:\n${scan.fingerprint}\n\nPin this host?")
                                .setPositiveButton("Pin") { _, _ ->
                                    Keys.pin(this, scan.line)
                                    status.text = "Host key pinned. Connection OK."
                                }
                                .setNegativeButton("Cancel", null)
                                .show()
                        }
                    }
                }
            }
        }
    }
}
