package invalid.lena.rsend

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

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

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

    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 { if (save()) finish() }
    }

    private fun save(): Boolean {
        val minutes = interval.text.toString().toIntOrNull()
        if (minutes == null || minutes < Schedule.MIN_INTERVAL_MINUTES) {
            Toast.makeText(
                this,
                "Interval must be at least ${Schedule.MIN_INTERVAL_MINUTES} minutes.",
                Toast.LENGTH_LONG,
            ).show()
            return false
        }
        val cfg = Config.load(this)
        val s = Schedule(
            enabled = enabled.isChecked,
            intervalMinutes = minutes,
            wifiOnly = wifiOnly.isChecked,
            requireCharging = charging.isChecked,
        )
        Config.save(this, cfg.copy(schedule = s))
        Scheduler.apply(this)
        return true
    }
}
