package invalid.lena.rsend

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.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

    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.save).setOnClickListener { 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() {
        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() },
        )
        if (f.local.isNotEmpty() && !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))
    }

    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))
        }
    }
}
