package invalid.lena.rsend

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Switch
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import java.io.File

// FolderEditActivity adds or edits one folder mapping. index < 0 means a new
// folder.
class FolderEditActivity : AppCompatActivity() {

    private var index: Int = -1
    private lateinit var name: EditText
    private lateinit var local: EditText
    private lateinit var remote: EditText
    private lateinit var excludes: EditText
    private lateinit var delete: Switch

    // The picker returns a real filesystem path; drop it into the local field and
    // name the folder after its basename if the name is still blank.
    private val pickFolder =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val path = result.data?.getStringExtra("path") ?: return@registerForActivityResult
                local.setText(path)
                if (name.text.isNullOrBlank()) name.setText(File(path).name)
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_folder)
        setSupportActionBar(findViewById(R.id.toolbar))
        title = "Folder"
        fitSystemBars()
        name = findViewById(R.id.name)
        local = findViewById(R.id.local)
        remote = findViewById(R.id.remote)
        excludes = findViewById(R.id.excludes)
        delete = findViewById(R.id.delete)

        index = intent.getIntExtra("index", -1)
        val cfg = Config.load(this)
        if (index in cfg.folders.indices) {
            val f = cfg.folders[index]
            name.setText(f.name)
            local.setText(f.local)
            remote.setText(f.remote)
            excludes.setText(f.excludes.joinToString(", "))
            delete.isChecked = f.delete
        }

        findViewById<Button>(R.id.browse).setOnClickListener {
            pickFolder.launch(
                Intent(this, FolderPickerActivity::class.java)
                    .putExtra("start", local.text.toString().trim())
            )
        }

        findViewById<Button>(R.id.save).setOnClickListener { if (saveFolder()) finish() }
        val del = findViewById<Button>(R.id.removeFolder)
        del.visibility = if (index < 0) View.GONE else View.VISIBLE
        del.setOnClickListener { removeFolder(); finish() }
    }

    private fun saveFolder(): Boolean {
        val f = Folder(
            name = name.text.toString().trim(),
            local = local.text.toString().trim(),
            remote = remote.text.toString().trim(),
            delete = delete.isChecked,
            excludes = excludes.text.toString().split(",").map { it.trim() }.filter { it.isNotEmpty() },
        )
        // An empty path would rsync / (local) or the rrsync root (remote):
        // refuse rather than sync the world.
        if (f.local.isEmpty() || f.remote.isEmpty()) {
            Toast.makeText(this, "Set both local and remote paths first.", Toast.LENGTH_LONG).show()
            return false
        }
        if (!File(f.local).exists()) {
            Toast.makeText(this, "Warning: local path does not exist yet.", Toast.LENGTH_LONG).show()
        }
        val cfg = Config.load(this)
        val list = cfg.folders.toMutableList()
        if (index in list.indices) list[index] = f else list.add(f)
        Config.save(this, cfg.copy(folders = list))
        return true
    }

    private fun removeFolder() {
        val cfg = Config.load(this)
        val list = cfg.folders.toMutableList()
        if (index in list.indices) {
            list.removeAt(index)
            Config.save(this, cfg.copy(folders = list))
        }
    }
}
