package invalid.lena.rsend

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Switch
import androidx.appcompat.app.AppCompatActivity

// ScheduleActivity edits the periodic sync settings and (re)applies them to
// WorkManager on save.
class ScheduleActivity : AppCompatActivity() {

    private lateinit var enabled: Switch
    private lateinit var interval: EditText
    private lateinit var wifiOnly: Switch
    private lateinit var charging: Switch

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_schedule)
        setSupportActionBar(findViewById(R.id.toolbar))
        title = "Schedule"
        fitSystemBars()
        enabled = findViewById(R.id.enabled)
        interval = findViewById(R.id.interval)
        wifiOnly = findViewById(R.id.wifiOnly)
        charging = findViewById(R.id.charging)

        val s = Config.load(this).schedule
        enabled.isChecked = s.enabled
        interval.setText(s.intervalMinutes.toString())
        wifiOnly.isChecked = s.wifiOnly
        charging.isChecked = s.requireCharging

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

    private fun save() {
        val cfg = Config.load(this)
        val s = Schedule(
            enabled = enabled.isChecked,
            intervalMinutes = interval.text.toString().toIntOrNull()
                ?.coerceAtLeast(Schedule.MIN_INTERVAL_MINUTES) ?: 120,
            wifiOnly = wifiOnly.isChecked,
            requireCharging = charging.isChecked,
        )
        Config.save(this, cfg.copy(schedule = s))
        Scheduler.apply(this)
    }
}
