package com.sshproxy.vpn

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import com.sshproxy.vpn.data.SshAuthMethod
import com.sshproxy.vpn.databinding.ActivityTunnelSettingsBinding
import com.sshproxy.vpn.ui.TunnelConfigForm

class TunnelSettingsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityTunnelSettingsBinding

    private val pickKeyLauncher = registerForActivityResult(
        ActivityResultContracts.OpenDocument()
    ) { uri ->
        if (uri == null) return@registerForActivityResult
        contentResolver.takePersistableUriPermission(
            uri,
            Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
        val path = KeyFileHelper.copyToInternal(this, uri)
        binding.keyPath.setText(path)
        saveDraft()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTunnelSettingsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = getString(R.string.tunnel_settings_title)

        val prefs = (application as TunnelApplication).prefs
        TunnelConfigForm.populate(binding, prefs.load())

        binding.toolbar.setNavigationOnClickListener { finish() }
        binding.pickKeyButton.setOnClickListener {
            pickKeyLauncher.launch(arrayOf("*/*"))
        }

        binding.authByPassword.setOnCheckedChangeListener { _, isChecked ->
            TunnelConfigForm.applyAuthSections(
                binding,
                if (isChecked) SshAuthMethod.PASSWORD else SshAuthMethod.PUBLIC_KEY
            )
            saveDraft()
        }

        listOf(
            binding.host,
            binding.port,
            binding.username,
            binding.keyPath,
            binding.socksPort,
            binding.remoteSocksHost,
            binding.remoteSocksPort,
            binding.remoteSocksUsername,
            binding.keepAliveInterval
        ).forEach { it.doAfterTextChanged { saveDraft() } }
        binding.remoteSocksPassword.doAfterTextChanged { saveDraft() }
        binding.passphrase.doAfterTextChanged { saveDraft() }
        binding.sshPassword.doAfterTextChanged { saveDraft() }
        binding.acceptUnknownHost.setOnCheckedChangeListener { _, _ -> saveDraft() }
        binding.autoReconnect.setOnCheckedChangeListener { _, _ -> saveDraft() }
    }

    override fun onPause() {
        saveDraft()
        super.onPause()
    }

    private fun saveDraft() {
        (application as TunnelApplication).prefs.save(TunnelConfigForm.read(binding))
    }
}
